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