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