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