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