]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
ba3bda6d95afbf728c5f8805381681f81d73d8ca
[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), 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 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 col_type InsetMathGrid::guessColumns(docstring const & hh)
282 {
283         col_type col = 0;
284         for (char_type const c : hh)
285                 if (c == 'c' || c == 'l' || c == 'r'||
286                     c == 'p' || c == 'm' || c == '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 col_type InsetMathGrid::ncols() const
343 {
344         return colinfo_.size() - 1;
345 }
346
347
348 row_type InsetMathGrid::nrows() const
349 {
350         return rowinfo_.size() - 1;
351 }
352
353
354 col_type InsetMathGrid::col(idx_type idx) const
355 {
356         return idx % ncols();
357 }
358
359
360 row_type InsetMathGrid::row(idx_type idx) const
361 {
362         return idx / ncols();
363 }
364
365
366 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[&bv] = 0;
428         for (row_type row = 1; row <= nrows(); ++row) {
429                 rowinfo_[row].offset[&bv] =
430                         rowinfo_[row - 1].offset[&bv] +
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[&bv];
446                         break;
447                 default:
448                         h = rowinfo_[nrows() - 1].offset[&bv] / 2;
449         }
450         for (row_type row = 0; row <= nrows(); ++row)
451                 rowinfo_[row].offset[&bv] -= 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[&bv]
532                 + rowinfo_[0].ascent
533                 + hlinesep() * rowinfo_[0].lines
534                 + border();
535
536         dim.des = rowinfo_[nrows() - 1].offset[&bv]
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(BufferView const & bv, row_type row,
612                                 unsigned int line) const
613 {
614         return rowinfo_[row].offset[&bv]
615                 - rowinfo_[row].ascent
616                 - line * hlinesep()
617                 - hlinesep()/2 - rowsep()/2;
618 }
619
620
621 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
622 {
623         BufferView const & bv = *pi.base.bv;
624
625         for (idx_type idx = 0; idx < nargs(); ++idx) {
626                 if (cellinfo_[idx].multi != CELL_PART_OF_MULTICOLUMN) {
627                         cell(idx).draw(pi,
628                                        x + leftMargin() + cellXOffset(bv, idx),
629                                        y + cellYOffset(bv, idx));
630
631                         row_type r = row(idx);
632                         int const yy1 = y + hLineVOffset(bv, r, 0);
633                         int const yy2 = y + hLineVOffset(bv, r + 1, rowinfo_[r + 1].lines - 1);
634                         auto draw_left_borders = [&](col_type c) {
635                                 for (unsigned int i = 0; i < colinfo_[c].lines; ++i) {
636                                         int const xx = x + vLineHOffset(c, i);
637                                         pi.pain.line(xx, yy1, xx, yy2, Color_foreground);
638                                 }
639                         };
640                         col_type c = col(idx);
641                         // Draw inner left borders cell-by-cell because of multicolumns
642                         draw_left_borders(c);
643                         // Draw the right border (only once)
644                         if (c == 0)
645                                 draw_left_borders(ncols());
646                 }
647         }
648
649         // Draw horizontal borders
650         for (row_type r = 0; r <= nrows(); ++r) {
651                 int const xx1 = x + vLineHOffset(0, 0);
652                 int const xx2 = x + vLineHOffset(ncols(), colinfo_[ncols()].lines - 1);
653                 for (unsigned int i = 0; i < rowinfo_[r].lines; ++i) {
654                         int const yy = y + hLineVOffset(bv, r, i);
655                         pi.pain.line(xx1, yy, xx2, yy, Color_foreground);
656                 }
657         }
658 }
659
660
661 void InsetMathGrid::metricsT(TextMetricsInfo const & /*mi*/, Dimension & /*dim*/) const
662 {
663 // FIXME: this does not compile anymore with offset being a map
664 // It is not worth fixing it at this point since the code is basically dead.
665 #if 0
666         // let the cells adjust themselves
667         for (idx_type i = 0; i < nargs(); ++i)
668                 if (cellinfo_[i].multi != CELL_PART_OF_MULTICOLUMN)
669                         cell(i).metricsT(mi, dim);
670
671         // compute absolute sizes of vertical structure
672         for (row_type row = 0; row < nrows(); ++row) {
673                 int asc  = 0;
674                 int desc = 0;
675                 for (col_type col = 0; col < ncols(); ++col) {
676                         idx_type const i = index(row, col);
677                         if (cellinfo_[i].multi != CELL_PART_OF_MULTICOLUMN) {
678                                 //MathData const & c = cell(i);
679                                 // FIXME: BROKEN!
680                                 Dimension dimc;
681                                 asc  = max(asc,  dimc.ascent());
682                                 desc = max(desc, dimc.descent());
683                         }
684                 }
685                 rowinfo_[row].ascent  = asc;
686                 rowinfo_[row].descent = desc;
687         }
688         rowinfo_[nrows()].ascent  = 0;
689         rowinfo_[nrows()].descent = 0;
690
691         // compute vertical offsets
692         rowinfo_[0].offset[&bv] = 0;
693         for (row_type row = 1; row <= nrows(); ++row) {
694                 rowinfo_[row].offset[&bv]  =
695                         rowinfo_[row - 1].offset  +
696                         rowinfo_[row - 1].descent +
697                         //rowinfo_[row - 1].skipPixels(mi) +
698                         1 + //rowsep() +
699                         //rowinfo_[row].lines * hlinesep() +
700                         rowinfo_[row].ascent;
701         }
702
703         // adjust vertical offset
704         int h = 0;
705         switch (v_align_) {
706                 case 't':
707                         h = 0;
708                         break;
709                 case 'b':
710                         h = rowinfo_[nrows() - 1].offset;
711                         break;
712                 default:
713                         h = rowinfo_[nrows() - 1].offset / 2;
714         }
715         for (row_type row = 0; row <= nrows(); ++row)
716                 rowinfo_[row].offset -= h;
717
718
719         // compute absolute sizes of horizontal structure
720         for (col_type col = 0; col < ncols(); ++col) {
721                 int wid = 0;
722                 for (row_type row = 0; row < nrows(); ++row) {
723                         // FIXME: BROKEN!
724                         //idx_type const i = index(row, col);
725                         //if (cellinfo_[i].multi != CELL_PART_OF_MULTICOLUMN)
726                         //      wid = max(wid, cell(i).width());
727                 }
728                 colinfo_[col].width = wid;
729         }
730         colinfo_[ncols()].width  = 0;
731
732         // compute horizontal offsets
733         colinfo_[0].offset = border();
734         for (col_type col = 1; col <= ncols(); ++col) {
735                 colinfo_[col].offset =
736                         colinfo_[col - 1].offset +
737                         colinfo_[col - 1].width +
738                         displayColSpace(col - 1) +
739                         1 ; //colsep() +
740                         //colinfo_[col].lines * vlinesep();
741         }
742
743
744         dim.wid  =  colinfo_[ncols() - 1].offset
745                        + colinfo_[ncols() - 1].width
746                  //+ vlinesep() * colinfo_[ncols()].lines
747                        + 2;
748
749         dim.asc  = -rowinfo_[0].offset
750                        + rowinfo_[0].ascent
751                  //+ hlinesep() * rowinfo_[0].lines
752                        + 1;
753
754         dim.des  =  rowinfo_[nrows() - 1].offset
755                        + rowinfo_[nrows() - 1].descent
756                  //+ hlinesep() * rowinfo_[nrows()].lines
757                        + 1;
758 #endif
759 }
760
761
762 void InsetMathGrid::drawT(TextPainter & /*pain*/, int /*x*/, int /*y*/) const
763 {
764 //      for (idx_type idx = 0; idx < nargs(); ++idx)
765 //              if (cellinfo_[idx].multi != CELL_PART_OF_MULTICOLUMN)
766 //                      cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
767 }
768
769
770 void InsetMathGrid::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
771 {
772         // pass down
773         for (idx_type idx = 0; idx < nargs(); ++idx)
774                 if (cellinfo_[idx].multi != CELL_PART_OF_MULTICOLUMN)
775                         cell(idx).updateBuffer(it, utype, deleted);
776 }
777
778
779 docstring InsetMathGrid::eolString(row_type row, bool fragile,
780                 bool /*latex*/, bool last_eoln) const
781 {
782         docstring eol;
783
784         if (!rowinfo_[row].crskip.zero())
785                 eol += '[' + from_utf8(rowinfo_[row].crskip.asLatexString()) + ']';
786         else if(!rowinfo_[row].allow_newpage)
787                 eol += '*';
788
789         // make sure an upcoming '[' does not break anything
790         if (row + 1 < nrows()) {
791                 MathData const & c = cell(index(row + 1, 0));
792                 if (!c.empty() && c.front()->getChar() == '[')
793                         //eol += "[0pt]";
794                         eol += "{}";
795         }
796
797         // only add \\ if necessary
798         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !last_eoln))
799                 return docstring();
800
801         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
802 }
803
804
805 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
806 {
807         if (col + 1 == lastcol)
808                 return docstring();
809         return from_ascii(" & ");
810 }
811
812
813 void InsetMathGrid::addRow(row_type row)
814 {
815         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
816         cells_.insert
817                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathData(buffer_));
818         cellinfo_.insert
819                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
820 }
821
822
823 void InsetMathGrid::delRow(row_type row)
824 {
825         if (nrows() == 1)
826                 return;
827
828         cells_type::iterator it = cells_.begin() + row * ncols();
829         cells_.erase(it, it + ncols());
830
831         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
832         cellinfo_.erase(jt, jt + ncols());
833
834         rowinfo_.erase(rowinfo_.begin() + row);
835 }
836
837
838 void InsetMathGrid::copyRow(row_type row)
839 {
840         addRow(row);
841         for (col_type col = 0; col < ncols(); ++col) {
842                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
843                 // copying the cell does not set the buffer
844                 cells_[(row + 1) * ncols() + col].setBuffer(*buffer_);
845         }
846 }
847
848
849 void InsetMathGrid::swapRow(row_type row)
850 {
851         if (nrows() == 1)
852                 return;
853         if (row + 1 == nrows())
854                 --row;
855         for (col_type col = 0; col < ncols(); ++col)
856                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
857 }
858
859
860 void InsetMathGrid::addCol(col_type newcol)
861 {
862         const col_type nc = ncols();
863         const row_type nr = nrows();
864         cells_type new_cells((nc + 1) * nr);
865         vector<CellInfo> new_cellinfo((nc + 1) * nr);
866
867         for (row_type row = 0; row < nr; ++row)
868                 for (col_type col = 0; col < nc; ++col) {
869                         new_cells[row * (nc + 1) + col + (col >= newcol)]
870                                 = cells_[row * nc + col];
871                         new_cellinfo[row * (nc + 1) + col + (col >= newcol)]
872                                 = cellinfo_[row * nc + col];
873                 }
874         swap(cells_, new_cells);
875         // copying cells loses the buffer reference
876         setBuffer(*buffer_);
877         swap(cellinfo_, new_cellinfo);
878
879         ColInfo inf;
880         inf.skip  = defaultColSpace(newcol);
881         inf.align = defaultColAlign(newcol);
882         colinfo_.insert(colinfo_.begin() + newcol, inf);
883 }
884
885
886 void InsetMathGrid::delCol(col_type col)
887 {
888         if (ncols() == 1)
889                 return;
890
891         cells_type tmpcells;
892         vector<CellInfo> tmpcellinfo;
893         for (col_type i = 0; i < nargs(); ++i)
894                 if (i % ncols() != col) {
895                         tmpcells.push_back(cells_[i]);
896                         tmpcellinfo.push_back(cellinfo_[i]);
897                 }
898         swap(cells_, tmpcells);
899         // copying cells loses the buffer reference
900         setBuffer(*buffer_);
901         swap(cellinfo_, tmpcellinfo);
902
903         colinfo_.erase(colinfo_.begin() + col);
904 }
905
906
907 void InsetMathGrid::copyCol(col_type col)
908 {
909         addCol(col+1);
910         for (row_type row = 0; row < nrows(); ++row) {
911                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
912                 // copying the cell does not set the buffer
913                 cells_[row * ncols() + col + 1].setBuffer(*buffer_);
914         }
915 }
916
917
918 void InsetMathGrid::swapCol(col_type col)
919 {
920         if (ncols() == 1)
921                 return;
922         if (col + 1 == ncols())
923                 --col;
924         for (row_type row = 0; row < nrows(); ++row)
925                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
926 }
927
928
929 int InsetMathGrid::cellXOffset(BufferView const & bv, idx_type idx) const
930 {
931         if (cellinfo_[idx].multi == CELL_PART_OF_MULTICOLUMN)
932                 return 0;
933         col_type c = col(idx);
934         int x = colinfo_[c].offset;
935         char align = displayColAlign(idx);
936         Dimension const & celldim = cell(idx).dimension(bv);
937         if (align == 'r' || align == 'R')
938                 x += cellWidth(idx) - celldim.wid;
939         if (align == 'c' || align == 'C')
940                 x += (cellWidth(idx) - celldim.wid) / 2;
941         return x;
942 }
943
944
945 int InsetMathGrid::cellYOffset(BufferView const & bv, idx_type idx) const
946 {
947         return rowinfo_[row(idx)].offset[&bv];
948 }
949
950
951 int InsetMathGrid::cellWidth(idx_type idx) const
952 {
953         switch (cellinfo_[idx].multi) {
954         case CELL_NORMAL:
955                 return colinfo_[col(idx)].width;
956         case CELL_BEGIN_OF_MULTICOLUMN: {
957                 col_type c1 = col(idx);
958                 col_type c2 = c1 + ncellcols(idx);
959                 return colinfo_[c2].offset
960                         - colinfo_[c1].offset
961                         - displayColSpace(c2)
962                         - colsep()
963                         - colinfo_[c2].lines * vlinesep();
964         }
965         case CELL_PART_OF_MULTICOLUMN:
966                 return 0;
967         }
968         return 0;
969 }
970
971
972 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
973 {
974         if (up) {
975                 if (cur.row() == 0)
976                         return false;
977                 cur.idx() -= ncols();
978         } else {
979                 if (cur.row() + 1 >= nrows())
980                         return false;
981                 cur.idx() += ncols();
982         }
983         // If we are in a multicolumn cell, move to the "real" cell
984         while (cellinfo_[cur.idx()].multi == CELL_PART_OF_MULTICOLUMN) {
985                 LASSERT(cur.idx() > 0, return false);
986                 --cur.idx();
987         }
988         // FIXME: this is only a workaround to avoid a crash if the inset
989         // in not in coord cache. The best would be to force a FitCursor
990         // operation.
991         CoordCache::Arrays const & arraysCache = cur.bv().coordCache().arrays();
992         if (arraysCache.has(&cur.cell()))
993                 cur.pos() = cur.cell().x2pos(&cur.bv(), cur.x_target() - cur.cell().xo(cur.bv()));
994         else
995                 cur.pos() = 0;
996         return true;
997 }
998
999
1000 bool InsetMathGrid::idxBackward(Cursor & cur) const
1001 {
1002         // leave matrix if at the front edge
1003         if (cur.col() == 0)
1004                 return false;
1005         --cur.idx();
1006         // If we are in a multicolumn cell, move to the "real" cell
1007         while (cellinfo_[cur.idx()].multi == CELL_PART_OF_MULTICOLUMN) {
1008                 LASSERT(cur.idx() > 0, return false);
1009                 --cur.idx();
1010         }
1011         cur.pos() = cur.lastpos();
1012         return true;
1013 }
1014
1015
1016 bool InsetMathGrid::idxForward(Cursor & cur) const
1017 {
1018         // leave matrix if at the back edge
1019         if (cur.col() + 1 == ncols())
1020                 return false;
1021         ++cur.idx();
1022         // If we are in a multicolumn cell, move to the next cell
1023         while (cellinfo_[cur.idx()].multi == CELL_PART_OF_MULTICOLUMN) {
1024                 // leave matrix if at the back edge
1025                 if (cur.col() + 1 == ncols())
1026                         return false;
1027                 ++cur.idx();
1028         }
1029         cur.pos() = 0;
1030         return true;
1031 }
1032
1033
1034 idx_type InsetMathGrid::firstIdx() const
1035 {
1036         size_type idx = 0;
1037         switch (v_align_) {
1038                 case 't':
1039                         //idx = 0;
1040                         break;
1041                 case 'b':
1042                         idx = (nrows() - 1) * ncols();
1043                         break;
1044                 default:
1045                         idx = ((nrows() - 1) / 2) * ncols();
1046         }
1047         // If we are in a multicolumn cell, move to the "real" cell
1048         while (cellinfo_[idx].multi == CELL_PART_OF_MULTICOLUMN) {
1049                 LASSERT(idx > 0, return 0);
1050                 --idx;
1051         }
1052         return idx;
1053 }
1054
1055
1056 idx_type InsetMathGrid::lastIdx() const
1057 {
1058         size_type idx = 0;
1059         switch (v_align_) {
1060                 case 't':
1061                         idx = ncols() - 1;
1062                         break;
1063                 case 'b':
1064                         idx = nargs() - 1;
1065                         break;
1066                 default:
1067                         idx = ((nrows() - 1) / 2 + 1) * ncols() - 1;
1068         }
1069         // If we are in a multicolumn cell, move to the "real" cell
1070         while (cellinfo_[idx].multi == CELL_PART_OF_MULTICOLUMN) {
1071                 LASSERT(idx > 0, return false);
1072                 --idx;
1073         }
1074         return idx;
1075 }
1076
1077
1078 bool InsetMathGrid::idxDelete(idx_type & idx)
1079 {
1080         // nothing to do if we have just one row
1081         if (nrows() == 1)
1082                 return false;
1083
1084         // nothing to do if we are in the middle of the last row of the inset
1085         if (idx + ncols() > nargs())
1086                 return false;
1087
1088         // try to delete entire sequence of ncols() empty cells if possible
1089         for (idx_type i = idx; i < idx + ncols(); ++i)
1090                 if (!cell(i).empty())
1091                         return false;
1092
1093         // move cells if necessary
1094         for (idx_type i = index(row(idx), 0); i < idx; ++i)
1095                 swap(cell(i), cell(i + ncols()));
1096
1097         delRow(row(idx));
1098
1099         if (idx >= nargs())
1100                 idx = nargs() - 1;
1101
1102         // undo effect of Ctrl-Tab (i.e. pull next cell)
1103         //if (idx + 1 != nargs())
1104         //      cell(idx).swap(cell(idx + 1));
1105
1106         // we handled the event..
1107         return true;
1108 }
1109
1110
1111 // reimplement old behaviour when pressing Delete in the last position
1112 // of a cell
1113 void InsetMathGrid::idxGlue(idx_type idx)
1114 {
1115         col_type c = col(idx);
1116         if (c + 1 == ncols()) {
1117                 if (row(idx) + 1 != nrows()) {
1118                         for (col_type cc = 0; cc < ncols(); ++cc)
1119                                 cell(idx).append(cell(idx + cc + 1));
1120                         delRow(row(idx) + 1);
1121                 }
1122         } else {
1123                 idx_type idx_next = idx + 1;
1124                 while (idx_next < nargs() &&
1125                        cellinfo_[idx_next].multi == CELL_PART_OF_MULTICOLUMN)
1126                         ++idx_next;
1127                 if (idx_next < nargs())
1128                         cell(idx).append(cell(idx_next));
1129                 col_type oldcol = c + 1;
1130                 for (col_type cc = c + 2; cc < ncols(); ++cc)
1131                         cell(idx - oldcol + cc) = cell(idx - oldcol + 1 + cc);
1132                 cell(idx - c + ncols() - 1).clear();
1133         }
1134 }
1135
1136
1137 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
1138 {
1139         return rowinfo_[row];
1140 }
1141
1142
1143 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
1144 {
1145         return rowinfo_[row];
1146 }
1147
1148
1149 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
1150 {
1151         row_type const ri = row(idx);
1152         row_type const r1 = min(row(from), row(to));
1153         row_type const r2 = max(row(from), row(to));
1154         col_type const ci = col(idx);
1155         col_type const c1 = min(col(from), col(to));
1156         col_type const c2 = max(col(from), col(to));
1157         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
1158 }
1159
1160
1161 void InsetMathGrid::normalize(NormalStream & os) const
1162 {
1163         os << "[grid ";
1164         for (row_type row = 0; row < nrows(); ++row) {
1165                 os << "[row ";
1166                 for (col_type col = 0; col < ncols(); ++col) {
1167                         idx_type const i = index(row, col);
1168                         switch (cellinfo_[i].multi) {
1169                         case CELL_NORMAL:
1170                                 os << "[cell " << cell(i) << ']';
1171                                 break;
1172                         case CELL_BEGIN_OF_MULTICOLUMN:
1173                                 os << "[cell colspan="
1174                                    << static_cast<int>(ncellcols(i)) << ' '
1175                                    << cell(i) << ']';
1176                                 break;
1177                         case CELL_PART_OF_MULTICOLUMN:
1178                                 break;
1179                         }
1180                 }
1181                 os << ']';
1182         }
1183         os << ']';
1184 }
1185
1186
1187 void InsetMathGrid::mathmlize(MathStream & ms) const
1188 {
1189         bool const havetable = nrows() > 1 || ncols() > 1;
1190         if (havetable)
1191                 ms << MTag("mtable");
1192         char const * const celltag = havetable ? "mtd" : "mrow";
1193         for (row_type row = 0; row < nrows(); ++row) {
1194                 if (havetable)
1195                         ms << MTag("mtr");
1196                 for (col_type col = 0; col < ncols(); ++col) {
1197                         idx_type const i = index(row, col);
1198                         if (cellinfo_[i].multi != CELL_PART_OF_MULTICOLUMN) {
1199                                 col_type const cellcols = ncellcols(i);
1200                                 ostringstream attr;
1201                                 if (havetable && cellcols > 1)
1202                                         attr << "colspan='" << cellcols << '\'';
1203                                 ms << MTag(celltag, attr.str());
1204                                 ms << cell(index(row, col));
1205                                 ms << ETag(celltag);
1206                         }
1207                 }
1208                 if (havetable)
1209                         ms << ETag("mtr");
1210         }
1211         if (havetable)
1212                 ms << ETag("mtable");
1213 }
1214
1215
1216 // FIXME XHTML
1217 // We need to do something about alignment here.
1218 void InsetMathGrid::htmlize(HtmlStream & os, string const & attrib) const
1219 {
1220         bool const havetable = nrows() > 1 || ncols() > 1;
1221         if (!havetable) {
1222                 os << cell(index(0, 0));
1223                 return;
1224         }
1225         os << MTag("table", attrib);
1226         for (row_type row = 0; row < nrows(); ++row) {
1227                 os << MTag("tr");
1228                 for (col_type col = 0; col < ncols(); ++col) {
1229                         idx_type const i = index(row, col);
1230                         if (cellinfo_[i].multi != CELL_PART_OF_MULTICOLUMN) {
1231                                 col_type const cellcols = ncellcols(i);
1232                                 ostringstream attr;
1233                                 if (cellcols > 1)
1234                                         attr << "colspan='" << cellcols << '\'';
1235                                 os << MTag("td", attr.str());
1236                                 os << cell(index(row, col));
1237                                 os << ETag("td");
1238                         }
1239                 }
1240                 os << ETag("tr");
1241         }
1242         os << ETag("table");
1243 }
1244
1245
1246 void InsetMathGrid::htmlize(HtmlStream & os) const
1247 {
1248         htmlize(os, "class='mathtable'");
1249 }
1250
1251
1252 void InsetMathGrid::validate(LaTeXFeatures & features) const
1253 {
1254         if (features.runparams().math_flavor == OutputParams::MathAsHTML
1255             && (nrows() > 1 || ncols() > 1)) {
1256                 // CSS taken from InsetMathCases
1257                 features.addCSSSnippet(
1258                         "table.mathtable{display: inline-block; text-align: center; border: none;"
1259                         "border-left: thin solid black; vertical-align: middle; padding-left: 0.5ex;}\n"
1260                         "table.mathtable td {text-align: left; border: none;}");
1261         }
1262         InsetMathNest::validate(features);
1263 }
1264
1265
1266 void InsetMathGrid::write(WriteStream & os) const
1267 {
1268         write(os, 0, 0, nrows(), ncols());
1269 }
1270
1271 void InsetMathGrid::write(WriteStream & os,
1272                           row_type beg_row, col_type beg_col,
1273                           row_type end_row, col_type end_col) const
1274 {
1275         MathEnsurer ensurer(os, false);
1276         docstring eol;
1277         for (row_type row = beg_row; row < end_row; ++row) {
1278                 os << verboseHLine(rowinfo_[row].lines);
1279                 // don't write & and empty cells at end of line,
1280                 // unless there are vertical lines
1281                 col_type lastcol = 0;
1282                 bool emptyline = true;
1283                 bool last_eoln = true;
1284                 for (col_type col = beg_col; col < end_col; ++col) {
1285                         idx_type const idx = index(row, col);
1286                         bool const empty_cell = cell(idx).empty();
1287                         if (!empty_cell || cellinfo_[idx].multi != CELL_NORMAL)
1288                                 last_eoln = false;
1289                         if (!empty_cell || cellinfo_[idx].multi != CELL_NORMAL ||
1290                             colinfo_[col + 1].lines) {
1291                                 lastcol = col + 1;
1292                                 emptyline = false;
1293                         }
1294                 }
1295                 for (col_type col = beg_col; col < end_col;) {
1296                         int nccols = 1;
1297                         idx_type const idx = index(row, col);
1298                         TexRow::RowEntry entry = TexRow::mathEntry(id(),idx);
1299                         os.texrow().start(entry);
1300                         if (col >= lastcol) {
1301                                 ++col;
1302                                 continue;
1303                         }
1304                         Changer dummy = os.changeRowEntry(entry);
1305                         if (cellinfo_[idx].multi == CELL_BEGIN_OF_MULTICOLUMN) {
1306                                 size_t s = col + 1;
1307                                 while (s < ncols() &&
1308                                        cellinfo_[index(row, s)].multi == CELL_PART_OF_MULTICOLUMN)
1309                                         s++;
1310                                 nccols = s - col;
1311                                 os << "\\multicolumn{" << nccols
1312                                    << "}{" << cellinfo_[idx].align
1313                                    << "}{";
1314                         }
1315                         os << cell(idx);
1316                         if (os.pendingBrace())
1317                                 ModeSpecifier specifier(os, TEXT_MODE);
1318                         if (cellinfo_[idx].multi == CELL_BEGIN_OF_MULTICOLUMN)
1319                                 os << '}';
1320                         os << eocString(col + nccols - 1, lastcol);
1321                         col += nccols;
1322                 }
1323                 eol = eolString(row, os.fragile(), os.latex(), last_eoln);
1324                 os << eol;
1325                 // append newline only if line wasn't completely empty
1326                 // and the formula is not written on a single line
1327                 bool const empty = emptyline && eol.empty();
1328                 if (!empty && nrows() > 1)
1329                         os << "\n";
1330         }
1331         // @TODO use end_row instead of nrows() ?
1332         docstring const s = verboseHLine(rowinfo_[nrows()].lines);
1333         if (!s.empty()) {
1334                 if (eol.empty()) {
1335                         if (os.fragile())
1336                                 os << "\\protect";
1337                         os << "\\\\";
1338                 }
1339                 os << s;
1340         }
1341 }
1342
1343
1344 int InsetMathGrid::colsep() const
1345 {
1346         return 6;
1347 }
1348
1349
1350 int InsetMathGrid::rowsep() const
1351 {
1352         return 6;
1353 }
1354
1355
1356 int InsetMathGrid::hlinesep() const
1357 {
1358         return 3;
1359 }
1360
1361
1362 int InsetMathGrid::vlinesep() const
1363 {
1364         return 3;
1365 }
1366
1367
1368 int InsetMathGrid::border() const
1369 {
1370         return 1;
1371 }
1372
1373
1374 void InsetMathGrid::splitCell(Cursor & cur)
1375 {
1376         if (cur.idx() == cur.lastidx())
1377                 return;
1378         MathData ar = cur.cell();
1379         ar.erase(0, cur.pos());
1380         cur.cell().erase(cur.pos(), cur.lastpos());
1381         ++cur.idx();
1382         while (cur.idx() << nargs() &&
1383                cellinfo_[cur.idx()].multi == CELL_BEGIN_OF_MULTICOLUMN)
1384                 ++cur.idx();
1385         cur.pos() = 0;
1386         cur.cell().insert(0, ar);
1387 }
1388
1389
1390 char InsetMathGrid::displayColAlign(idx_type idx) const
1391 {
1392         if (cellinfo_[idx].multi == CELL_BEGIN_OF_MULTICOLUMN) {
1393                 // align may also contain lines like "||r|", so this is
1394                 // not complete, but we catch at least the simple cases.
1395                 if (cellinfo_[idx].align == "c")
1396                         return 'c';
1397                 if (cellinfo_[idx].align == "l")
1398                         return 'l';
1399                 if (cellinfo_[idx].align == "r")
1400                         return 'r';
1401         }
1402         return colinfo_[col(idx)].align;
1403 }
1404
1405
1406 int InsetMathGrid::displayColSpace(col_type col) const
1407 {
1408         return colinfo_[col].skip;
1409 }
1410
1411 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1412 {
1413         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1414
1415         Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
1416
1417         FuncCode const act = cmd.action();
1418         switch (act) {
1419
1420         // insert file functions
1421         case LFUN_LINE_DELETE_FORWARD:
1422                 cur.recordUndoInset();
1423                 //autocorrect_ = false;
1424                 //macroModeClose();
1425                 //if (selection_) {
1426                 //      selDel();
1427                 //      break;
1428                 //}
1429                 if (nrows() > 1)
1430                         delRow(cur.row());
1431                 if (cur.idx() > cur.lastidx())
1432                         cur.idx() = cur.lastidx();
1433                 if (cur.pos() > cur.lastpos())
1434                         cur.pos() = cur.lastpos();
1435                 break;
1436
1437         case LFUN_CELL_SPLIT:
1438                 cur.recordUndo();
1439                 splitCell(cur);
1440                 break;
1441
1442         case LFUN_NEWLINE_INSERT: {
1443                 cur.recordUndoInset();
1444                 row_type const r = cur.row();
1445                 addRow(r);
1446
1447                 // split line
1448                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1449                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1450
1451                 // split cell
1452                 splitCell(cur);
1453                 if (ncols() > 1)
1454                         swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1455                 if (cur.idx() > 0)
1456                         --cur.idx();
1457                 cur.pos() = cur.lastpos();
1458                 cur.forceBufferUpdate();
1459                 //mathcursor->normalize();
1460                 //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1461                 break;
1462         }
1463
1464         case LFUN_TABULAR_FEATURE: {
1465                 cur.recordUndoInset();
1466                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1467                 istringstream is(to_utf8(cmd.argument()));
1468                 string s;
1469                 is >> s;
1470                 if (s == "valign-top")
1471                         setVerticalAlignment('t');
1472                 else if (s == "valign-middle")
1473                         setVerticalAlignment('c');
1474                 else if (s == "valign-bottom")
1475                         setVerticalAlignment('b');
1476                 else if (s == "align-left")
1477                         setHorizontalAlignment('l', cur.col());
1478                 else if (s == "align-right")
1479                         setHorizontalAlignment('r', cur.col());
1480                 else if (s == "align-center")
1481                         setHorizontalAlignment('c', cur.col());
1482                 else if (s == "append-row")
1483                         for (int i = 0, n = extractInt(is); i < n; ++i)
1484                                 addRow(cur.row());
1485                 else if (s == "delete-row") {
1486                         cur.clearSelection(); // bug 4323
1487                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1488                                 delRow(cur.row());
1489                                 if (cur.idx() >= nargs())
1490                                         cur.idx() -= ncols();
1491                         }
1492                         cur.pos() = 0; // trick, see below
1493                 }
1494                 else if (s == "copy-row") {
1495                         // Here (as later) we save the cursor col/row
1496                         // in order to restore it after operation.
1497                         row_type const r = cur.row();
1498                         col_type const c = cur.col();
1499                         for (int i = 0, n = extractInt(is); i < n; ++i)
1500                                 copyRow(cur.row());
1501                         cur.idx() = index(r, c);
1502                 }
1503                 else if (s == "swap-row") {
1504                         swapRow(cur.row());
1505                         // Trick to suppress same-idx-means-different-cell
1506                         // assertion crash:
1507                         cur.pos() = 0;
1508                 }
1509                 else if (s == "add-hline-above")
1510                         rowinfo_[cur.row()].lines++;
1511                 else if (s == "add-hline-below")
1512                         rowinfo_[cur.row()+1].lines++;
1513                 else if (s == "delete-hline-above")
1514                         rowinfo_[cur.row()].lines--;
1515                 else if (s == "delete-hline-below")
1516                         rowinfo_[cur.row()+1].lines--;
1517                 else if (s == "append-column") {
1518                         row_type const r = cur.row();
1519                         col_type const c = cur.col();
1520                         for (int i = 0, n = extractInt(is); i < n; ++i)
1521                                 addCol(cur.col() + 1);
1522                         cur.idx() = index(r, c);
1523                 }
1524                 else if (s == "delete-column") {
1525                         cur.clearSelection(); // bug 4323
1526                         row_type const r = cur.row();
1527                         col_type const c = cur.col();
1528                         for (int i = 0, n = extractInt(is); i < n; ++i)
1529                                 delCol(col(cur.idx()));
1530                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1531                         cur.pos() = 0; // trick, see above
1532                 }
1533                 else if (s == "copy-column") {
1534                         row_type const r = cur.row();
1535                         col_type const c = cur.col();
1536                         copyCol(cur.col());
1537                         cur.idx() = index(r, c);
1538                 }
1539                 else if (s == "swap-column") {
1540                         swapCol(cur.col());
1541                         cur.pos() = 0; // trick, see above
1542                 }
1543                 else if (s == "add-vline-left") {
1544                         colinfo_[cur.col()].lines++;
1545                         if (!colinfo_[cur.col()].special.empty())
1546                                 colinfo_[cur.col()].special += '|';
1547                 }
1548                 else if (s == "add-vline-right") {
1549                         colinfo_[cur.col()+1].lines++;
1550                         if (!colinfo_[cur.col()+1].special.empty())
1551                                 colinfo_[cur.col()+1].special.insert(0, 1, '|');
1552                 }
1553                 else if (s == "delete-vline-left") {
1554                         colinfo_[cur.col()].lines--;
1555                         docstring & special = colinfo_[cur.col()].special;
1556                         if (!special.empty()) {
1557                                 docstring::size_type i = special.rfind('|');
1558                                 LASSERT(i != docstring::npos, break);
1559                                 special.erase(i, 1);
1560                         }
1561                 }
1562                 else if (s == "delete-vline-right") {
1563                         colinfo_[cur.col()+1].lines--;
1564                         docstring & special = colinfo_[cur.col()+1].special;
1565                         if (!special.empty()) {
1566                                 docstring::size_type i = special.find('|');
1567                                 LASSERT(i != docstring::npos, break);
1568                                 special.erase(i, 1);
1569                         }
1570                 }
1571                 else {
1572                         cur.undispatched();
1573                         break;
1574                 }
1575                 // perhaps this should be FINISHED_BACKWARD -- just for clarity?
1576                 //lyxerr << "returning FINISHED_LEFT" << endl;
1577                 break;
1578         }
1579
1580         case LFUN_CLIPBOARD_PASTE:
1581                 parseflg |= Parse::VERBATIM;
1582                 // fall through
1583         case LFUN_PASTE: {
1584                 if (cur.currentMode() != MATH_MODE)
1585                         parseflg |= Parse::TEXTMODE;
1586                 cur.message(_("Paste"));
1587                 cap::replaceSelection(cur);
1588                 docstring topaste;
1589                 if (cmd.argument().empty() && !theClipboard().isInternal())
1590                         topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
1591                 else {
1592                         idocstringstream is(cmd.argument());
1593                         int n = 0;
1594                         is >> n;
1595                         topaste = cap::selection(n, buffer().params().documentClassPtr());
1596                 }
1597                 InsetMathGrid grid(buffer_, 1, 1);
1598                 if (!topaste.empty())
1599                         if ((topaste.size() == 1 && isAscii(topaste))
1600                             || !mathed_parse_normal(grid, topaste, parseflg)) {
1601                                 resetGrid(grid);
1602                                 mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
1603                         }
1604
1605                 bool hline_enabled = false;
1606                 FuncRequest fr = FuncRequest(LFUN_TABULAR_FEATURE, "add-hline-above");
1607                 FuncStatus status;
1608                 if (getStatus(cur, fr, status))
1609                         hline_enabled = status.enabled();
1610                 if (grid.nargs() == 1) {
1611                         // single cell/part of cell
1612                         cur.recordUndoInset();
1613                         cur.cell().insert(cur.pos(), grid.cell(0));
1614                         cur.pos() += grid.cell(0).size();
1615                         if (hline_enabled)
1616                                 rowinfo_[cur.row()].lines += grid.rowinfo_[0].lines;
1617                         else {
1618                                 for (unsigned int l = 0; l < grid.rowinfo_[0].lines; ++l) {
1619                                          cur.cell().insert(0,
1620                                                 MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1621                                          cur.pos()++;
1622                                 }
1623                         }
1624                 } else {
1625                         // multiple cells
1626                         cur.recordUndoInset();
1627                         col_type startcol = col(cur.idx());
1628                         row_type startrow = cur.row();
1629                         col_type oldncols = ncols();
1630                         col_type numcols =
1631                                 min(grid.ncols(), ncols() - startcol);
1632                         row_type const numrows =
1633                                 min(grid.nrows(), nrows() - cur.row());
1634                         for (row_type r = 0; r < numrows; ++r) {
1635                                 for (col_type c = 0; c < numcols; ++c) {
1636                                         idx_type i = index(r + startrow, c + startcol);
1637                                         pos_type const ipos = min(cur.pos(), pos_type(cell(i).size()));
1638                                         cell(i).insert(ipos, 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 + startrow, 0);
1645                                                 cell(i).insert(0,
1646                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1647                                         }
1648                                 }
1649                                 // append columns for the left over horizontal cells
1650                                 for (col_type c = numcols; c < grid.ncols(); ++c) {
1651                                         addCol(c + startcol);
1652                                         idx_type i = index(r + startrow, min(c + startcol, ncols() - 1));
1653                                         cell(i).append(grid.cell(grid.index(r, c)));
1654                                         ++numcols;
1655                                 }
1656                         }
1657                         // amend cursor position if cols have been appended
1658                         cur.idx() += startrow * (ncols() - oldncols);
1659                         // append rows for the left over vertical cells
1660                         idx_type i = nargs() - 1;
1661                         for (row_type r = numrows; r < grid.nrows(); ++r) {
1662                                 row_type crow = startrow + r;
1663                                 addRow(crow - 1);
1664                                 for (col_type c = 0; c < grid.ncols(); ++c)
1665                                         cell(index(min(crow, nrows() - 1), min(c + startcol, ncols() - 1))).append(grid.cell(grid.index(r, c)));
1666                                 if (hline_enabled)
1667                                         rowinfo_[crow].lines += grid.rowinfo_[r].lines;
1668                                 else {
1669                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines; ++l) {
1670                                                 cell(i).insert(0,
1671                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1672                                         }
1673                                 }
1674                         }
1675                 }
1676                 cur.clearSelection(); // bug 393
1677                 // FIXME audit setBuffer calls
1678                 cur.inset().setBuffer(*buffer_);
1679                 cur.forceBufferUpdate();
1680                 cur.finishUndo();
1681                 break;
1682         }
1683
1684         case LFUN_LINE_BEGIN:
1685                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1686                 // fall through
1687         case LFUN_LINE_BEGIN_SELECT:
1688                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1689                                 act == LFUN_WORD_LEFT_SELECT ||
1690                                 act == LFUN_LINE_BEGIN_SELECT);
1691                 cur.macroModeClose();
1692                 if (cur.pos() != 0) {
1693                         cur.pos() = 0;
1694                 } else if (cur.idx() % cur.ncols() != 0) {
1695                         cur.idx() -= cur.idx() % cur.ncols();
1696                         cur.pos() = 0;
1697                 } else if (cur.idx() != 0) {
1698                         cur.idx() = 0;
1699                         cur.pos() = 0;
1700                 } else {
1701                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1702                         cur.undispatched();
1703                 }
1704                 break;
1705
1706         case LFUN_LINE_END:
1707                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1708                 // fall through
1709         case LFUN_LINE_END_SELECT:
1710                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1711                                 act == LFUN_WORD_RIGHT_SELECT ||
1712                                 act == LFUN_LINE_END_SELECT);
1713                 cur.macroModeClose();
1714                 cur.clearTargetX();
1715                 if (cur.pos() != cur.lastpos()) {
1716                         cur.pos() = cur.lastpos();
1717                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1718                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1719                         cur.pos() = cur.lastpos();
1720                 } else if (cur.idx() != cur.lastidx()) {
1721                         cur.idx() = cur.lastidx();
1722                         cur.pos() = cur.lastpos();
1723                 } else {
1724                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1725                         cur.undispatched();
1726                 }
1727                 break;
1728
1729         default:
1730                 InsetMathNest::doDispatch(cur, cmd);
1731         }
1732 }
1733
1734
1735 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1736                 FuncStatus & status) const
1737 {
1738         switch (cmd.action()) {
1739         case LFUN_TABULAR_FEATURE: {
1740                 string s = cmd.getArg(0);
1741                 if (&cur.inset() != this) {
1742                         // Table actions requires that the cursor is _inside_ the
1743                         // table.
1744                         status.setEnabled(false);
1745                         status.message(from_utf8(N_("Cursor not in table")));
1746                         return true;
1747                 }
1748                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1749                         status.setEnabled(false);
1750                         status.message(from_utf8(N_("Only one row")));
1751                         return true;
1752                 }
1753                 if (ncols() <= 1 &&
1754                     (s == "delete-column" || s == "swap-column")) {
1755                         status.setEnabled(false);
1756                         status.message(from_utf8(N_("Only one column")));
1757                         return true;
1758                 }
1759                 if ((rowinfo_[cur.row()].lines == 0 &&
1760                      s == "delete-hline-above") ||
1761                     (rowinfo_[cur.row() + 1].lines == 0 &&
1762                      s == "delete-hline-below")) {
1763                         status.setEnabled(false);
1764                         status.message(from_utf8(N_("No hline to delete")));
1765                         return true;
1766                 }
1767
1768                 if ((colinfo_[cur.col()].lines == 0 &&
1769                      s == "delete-vline-left") ||
1770                     (colinfo_[cur.col() + 1].lines == 0 &&
1771                      s == "delete-vline-right")) {
1772                         status.setEnabled(false);
1773                         status.message(from_utf8(N_("No vline to delete")));
1774                         return true;
1775                 }
1776                 if (s == "valign-top" || s == "valign-middle" ||
1777                     s == "valign-bottom" || s == "align-left" ||
1778                     s == "align-right" || s == "align-center") {
1779                         status.setEnabled(true);
1780                         char const ha = horizontalAlignment(cur.col());
1781                         char const va = verticalAlignment();
1782                         status.setOnOff((s == "align-left" && ha == 'l')
1783                                         || (s == "align-right"   && ha == 'r')
1784                                         || (s == "align-center"  && ha == 'c')
1785                                         || (s == "valign-top"    && va == 't')
1786                                         || (s == "valign-bottom" && va == 'b')
1787                                         || (s == "valign-middle" && va == 'c'));
1788                         return true;
1789                 }
1790                 if (s == "append-row" || s == "delete-row" ||
1791                     s == "copy-row" || s == "swap-row" ||
1792                     s == "add-hline-above" || s == "add-hline-below" ||
1793                     s == "delete-hline-above" || s == "delete-hline-below" ||
1794                     s == "append-column" || s == "delete-column" ||
1795                     s == "copy-column" || s == "swap-column" ||
1796                     s == "add-vline-left" || s == "add-vline-right" ||
1797                     s == "delete-vline-left" || s == "delete-vline-right") {
1798                         status.setEnabled(true);
1799                 } else {
1800                         status.setEnabled(false);
1801                         status.message(bformat(
1802                             from_utf8(N_("Unknown tabular feature '%1$s'")),
1803                             from_utf8(s)));
1804                 }
1805
1806                 return true;
1807         }
1808
1809         case LFUN_CELL_SPLIT:
1810                 status.setEnabled(cur.idx() != cur.lastidx());
1811                 return true;
1812
1813         case LFUN_CELL_BACKWARD:
1814         case LFUN_CELL_FORWARD:
1815                 status.setEnabled(true);
1816                 return true;
1817
1818         default:
1819                 break;
1820         }
1821         return InsetMathNest::getStatus(cur, cmd, status);
1822 }
1823
1824
1825 char InsetMathGrid::colAlign(HullType type, col_type col) const
1826 {
1827         switch (type) {
1828         case hullEqnArray:
1829                 return "rcl"[col % 3];
1830
1831         case hullMultline:
1832                 return 'c';
1833         case hullGather:
1834                 LASSERT(isBufferValid(),
1835                                 LYXERR0("Buffer not set correctly. Please report!");
1836                                 return 'c';);
1837                 if (buffer().params().is_math_indent)
1838                         return 'l';
1839                 else
1840                         return 'c';
1841
1842         case hullAlign:
1843         case hullAlignAt:
1844         case hullXAlignAt:
1845         case hullXXAlignAt:
1846         case hullFlAlign:
1847                 return "rl"[col & 1];
1848
1849         case hullUnknown:
1850         case hullNone:
1851         case hullSimple:
1852         case hullEquation:
1853         case hullRegexp:
1854                 return 'c';
1855         }
1856         // avoid warning
1857         return 'c';
1858 }
1859
1860
1861 //static
1862 int InsetMathGrid::colSpace(HullType type, col_type col)
1863 {
1864         int alignInterSpace = 0;
1865         switch (type) {
1866         case hullUnknown:
1867         case hullNone:
1868         case hullSimple:
1869         case hullEquation:
1870         case hullMultline:
1871         case hullGather:
1872         case hullRegexp:
1873                 return 0;
1874
1875         case hullEqnArray:
1876                 return 5;
1877
1878         case hullAlign:
1879                 alignInterSpace = 20;
1880                 break;
1881         case hullAlignAt:
1882                 alignInterSpace = 0;
1883                 break;
1884         case hullXAlignAt:
1885                 alignInterSpace = 40;
1886                 break;
1887         case hullXXAlignAt:
1888         case hullFlAlign:
1889                 alignInterSpace = 60;
1890                 break;
1891         }
1892         return (col % 2) ? alignInterSpace : 0;
1893 }
1894
1895
1896 } // namespace lyx