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