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