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