]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
ada03bb8e528734a24b36318167f57b5d72f993a
[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 "MathData.h"
17 #include "MathParser.h"
18 #include "MathStream.h"
19 #include "MetricsInfo.h"
20
21 #include "Buffer.h"
22 #include "BufferView.h"
23 #include "CutAndPaste.h"
24 #include "FuncStatus.h"
25 #include "Cursor.h"
26 #include "FuncRequest.h"
27
28 #include "frontends/Clipboard.h"
29 #include "frontends/FontMetrics.h"
30 #include "frontends/Painter.h"
31
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36
37 #include "support/lassert.h"
38
39 #include <sstream>
40
41 using namespace std;
42 using namespace lyx::support;
43
44
45
46 namespace lyx {
47
48 static docstring verboseHLine(int n)
49 {
50         docstring res;
51         for (int i = 0; i < n; ++i)
52                 res += "\\hline";
53         if (n)
54                 res += ' ';
55         return res;
56 }
57
58
59 static int extractInt(istream & is)
60 {
61         int num = 1;
62         is >> num;
63         return (num == 0) ? 1 : num;
64 }
65
66
67 static void resetGrid(InsetMathGrid & grid)
68 {
69         while (grid.ncols() > 1)
70                 grid.delCol(grid.ncols());
71         while (grid.nrows() > 1)
72                 grid.delRow(grid.nrows());
73         grid.cell(0).erase(0, grid.cell(0).size());
74         grid.setDefaults();
75 }
76
77
78
79 //////////////////////////////////////////////////////////////
80
81
82 InsetMathGrid::CellInfo::CellInfo()
83         : dummy_(false)
84 {}
85
86
87
88 //////////////////////////////////////////////////////////////
89
90
91 InsetMathGrid::RowInfo::RowInfo()
92         : lines_(0), skip_(0), allow_newpage_(true)
93 {}
94
95
96
97 int InsetMathGrid::RowInfo::skipPixels(MetricsInfo const & mi) const
98 {
99         frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
100         return crskip_.inPixels(mi.base.textwidth,
101                                 fm.width(char_type('M')));
102 }
103
104
105
106 //////////////////////////////////////////////////////////////
107
108
109 InsetMathGrid::ColInfo::ColInfo()
110         : align_('c'), lines_(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 }
177
178
179 void InsetMathGrid::setHorizontalAlignments(docstring const & hh)
180 {
181         col_type col = 0;
182         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it) {
183                 char_type c = *it;
184                 if (c == '|') {
185                         colinfo_[col].lines_++;
186                 } else if ((c == 'p' || c == 'm' || c == 'b'||
187                             c == '!' || c == '@' || c == '>' || c == '<') &&
188                            it + 1 != hh.end() && *(it + 1) == '{') {
189                         // @{decl.} and p{width} are standard LaTeX, the
190                         // others are extensions by array.sty
191                         bool const newcolumn = c == 'p' || c == 'm' || c == 'b';
192                         if (newcolumn) {
193                                 // this declares a new column
194                                 if (col >= ncols())
195                                         // Only intercolumn stuff is allowed
196                                         // in the last dummy column
197                                         break;
198                                 colinfo_[col].align_ = 'l';
199                         } else {
200                                 // this is intercolumn stuff
201                                 if (colinfo_[col].special_.empty())
202                                         // Overtake possible lines
203                                         colinfo_[col].special_ = docstring(colinfo_[col].lines_, '|');
204                         }
205                         int brace_open = 0;
206                         int brace_close = 0;
207                         while (it != hh.end()) {
208                                 c = *it;
209                                 colinfo_[col].special_ += c;
210                                 if (c == '{')
211                                         ++brace_open;
212                                 else if (c == '}')
213                                         ++brace_close;
214                                 ++it;
215                                 if (brace_open > 0 && brace_open == brace_close)
216                                         break;
217                         }
218                         --it;
219                         if (newcolumn) {
220                                 colinfo_[col].lines_ = count(
221                                         colinfo_[col].special_.begin(),
222                                         colinfo_[col].special_.end(), '|');
223                                 LYXERR(Debug::MATHED, "special column separator: `"
224                                         << to_utf8(colinfo_[col].special_) << '\'');
225                                 ++col;
226                                 colinfo_[col].lines_ = 0;
227                                 colinfo_[col].special_.clear();
228                         }
229                 } else if (col >= ncols()) {
230                         // Only intercolumn stuff is allowed in the last
231                         // dummy column
232                         break;
233                 } else if (c == 'c' || c == 'l' || c == 'r') {
234                         colinfo_[col].align_ = static_cast<char>(c);
235                         if (!colinfo_[col].special_.empty()) {
236                                 colinfo_[col].special_ += c;
237                                 colinfo_[col].lines_ = count(
238                                                 colinfo_[col].special_.begin(),
239                                                 colinfo_[col].special_.end(), '|');
240                                 LYXERR(Debug::MATHED, "special column separator: `"
241                                         << to_utf8(colinfo_[col].special_) << '\'');
242                         }
243                         ++col;
244                         colinfo_[col].lines_ = 0;
245                         colinfo_[col].special_.clear();
246                 } else {
247                         lyxerr << "unknown column separator: '" << c << "'" << endl;
248                 }
249         }
250
251 /*
252         col_type n = hh.size();
253         if (n > ncols())
254                 n = ncols();
255         for (col_type col = 0; col < n; ++col)
256                 colinfo_[col].align_ = hh[col];
257 */
258 }
259
260
261 InsetMathGrid::col_type InsetMathGrid::guessColumns(docstring const & hh)
262 {
263         col_type col = 0;
264         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it)
265                 if (*it == 'c' || *it == 'l' || *it == 'r'||
266                     *it == 'p' || *it == 'm' || *it == 'b')
267                         ++col;
268         // let's have at least one column, even if we did not recognize its
269         // alignment
270         if (col == 0)
271                 col = 1;
272         return col;
273 }
274
275
276 void InsetMathGrid::setHorizontalAlignment(char h, col_type col)
277 {
278         colinfo_[col].align_ = h;
279         if (!colinfo_[col].special_.empty()) {
280                 char_type & c = colinfo_[col].special_[colinfo_[col].special_.size() - 1];
281                 if (c == 'l' || c == 'c' || c == 'r')
282                         c = h;
283         }
284         // FIXME: Change alignment of p, m and b columns, too
285 }
286
287
288 char InsetMathGrid::horizontalAlignment(col_type col) const
289 {
290         return colinfo_[col].align_;
291 }
292
293
294 docstring InsetMathGrid::horizontalAlignments() const
295 {
296         docstring res;
297         for (col_type col = 0; col < ncols(); ++col) {
298                 if (colinfo_[col].special_.empty()) {
299                         res += docstring(colinfo_[col].lines_, '|');
300                         res += colinfo_[col].align_;
301                 } else
302                         res += colinfo_[col].special_;
303         }
304         if (colinfo_[ncols()].special_.empty())
305                 return res + docstring(colinfo_[ncols()].lines_, '|');
306         return res + colinfo_[ncols()].special_;
307 }
308
309
310 void InsetMathGrid::setVerticalAlignment(char c)
311 {
312         v_align_ = c;
313 }
314
315
316 char InsetMathGrid::verticalAlignment() const
317 {
318         return v_align_;
319 }
320
321
322 InsetMathGrid::col_type InsetMathGrid::ncols() const
323 {
324         return colinfo_.size() - 1;
325 }
326
327
328 InsetMathGrid::row_type InsetMathGrid::nrows() const
329 {
330         return rowinfo_.size() - 1;
331 }
332
333
334 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
335 {
336         return idx % ncols();
337 }
338
339
340 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
341 {
342         return idx / ncols();
343 }
344
345
346 void InsetMathGrid::vcrskip(Length const & crskip, row_type row)
347 {
348         rowinfo_[row].crskip_ = crskip;
349 }
350
351
352 Length InsetMathGrid::vcrskip(row_type row) const
353 {
354         return rowinfo_[row].crskip_;
355 }
356
357
358 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
359 {
360         // let the cells adjust themselves
361         InsetMathNest::metrics(mi);
362
363         BufferView & bv = *mi.base.bv;
364
365         // compute absolute sizes of vertical structure
366         for (row_type row = 0; row < nrows(); ++row) {
367                 int asc  = 0;
368                 int desc = 0;
369                 for (col_type col = 0; col < ncols(); ++col) {
370                         Dimension const & dimc = cell(index(row, col)).dimension(bv);
371                         asc  = max(asc,  dimc.asc);
372                         desc = max(desc, dimc.des);
373                 }
374                 rowinfo_[row].ascent_  = asc;
375                 rowinfo_[row].descent_ = desc;
376         }
377         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
378         rowinfo_[nrows()].ascent_  = 0;
379         rowinfo_[nrows()].descent_ = 0;
380
381         // compute vertical offsets
382         rowinfo_[0].offset_ = 0;
383         for (row_type row = 1; row <= nrows(); ++row) {
384                 rowinfo_[row].offset_  =
385                         rowinfo_[row - 1].offset_  +
386                         rowinfo_[row - 1].descent_ +
387                         rowinfo_[row - 1].skipPixels(mi) +
388                         rowsep() +
389                         rowinfo_[row].lines_ * hlinesep() +
390                         rowinfo_[row].ascent_;
391         }
392
393         // adjust vertical offset
394         int h = 0;
395         switch (v_align_) {
396                 case 't':
397                         h = 0;
398                         break;
399                 case 'b':
400                         h = rowinfo_[nrows() - 1].offset_;
401                         break;
402                 default:
403                         h = rowinfo_[nrows() - 1].offset_ / 2;
404         }
405         for (row_type row = 0; row <= nrows(); ++row)
406                 rowinfo_[row].offset_ -= h;
407
408
409         // compute absolute sizes of horizontal structure
410         for (col_type col = 0; col < ncols(); ++col) {
411                 int wid = 0;
412                 for (row_type row = 0; row < nrows(); ++row)
413                         wid = max(wid, cell(index(row, col)).dimension(bv).wid);
414                 colinfo_[col].width_ = wid;
415         }
416         colinfo_[ncols()].width_  = 0;
417
418         // compute horizontal offsets
419         colinfo_[0].offset_ = border();
420         for (col_type col = 1; col <= ncols(); ++col) {
421                 colinfo_[col].offset_ =
422                         colinfo_[col - 1].offset_ +
423                         colinfo_[col - 1].width_ +
424                         colinfo_[col - 1].skip_ +
425                         colsep() +
426                         colinfo_[col].lines_ * vlinesep();
427         }
428
429
430         dim.wid   =   colinfo_[ncols() - 1].offset_
431                        + colinfo_[ncols() - 1].width_
432                  + vlinesep() * colinfo_[ncols()].lines_
433                        + border();
434
435         dim.asc  = - rowinfo_[0].offset_
436                        + rowinfo_[0].ascent_
437                  + hlinesep() * rowinfo_[0].lines_
438                        + border();
439
440         dim.des =   rowinfo_[nrows() - 1].offset_
441                        + rowinfo_[nrows() - 1].descent_
442                  + hlinesep() * rowinfo_[nrows()].lines_
443                        + border();
444
445
446 /*
447         // Increase ws_[i] for 'R' columns (except the first one)
448         for (int i = 1; i < nc_; ++i)
449                 if (align_[i] == 'R')
450                         ws_[i] += 10 * df_width;
451         // Increase ws_[i] for 'C' column
452         if (align_[0] == 'C')
453                 if (ws_[0] < 7 * workwidth / 8)
454                         ws_[0] = 7 * workwidth / 8;
455
456         // Adjust local tabs
457         width = colsep();
458         for (cxrow = row_.begin(); cxrow; ++cxrow) {
459                 int rg = COLSEP;
460                 int lf = 0;
461                 for (int i = 0; i < nc_; ++i) {
462                         bool isvoid = false;
463                         if (cxrow->getTab(i) <= 0) {
464                                 cxrow->setTab(i, df_width);
465                                 isvoid = true;
466                         }
467                         switch (align_[i]) {
468                         case 'l':
469                                 lf = 0;
470                                 break;
471                         case 'c':
472                                 lf = (ws_[i] - cxrow->getTab(i))/2;
473                                 break;
474                         case 'r':
475                         case 'R':
476                                 lf = ws_[i] - cxrow->getTab(i);
477                                 break;
478                         case 'C':
479                                 if (cxrow == row_.begin())
480                                         lf = 0;
481                                 else if (cxrow.is_last())
482                                         lf = ws_[i] - cxrow->getTab(i);
483                                 else
484                                         lf = (ws_[i] - cxrow->getTab(i))/2;
485                                 break;
486                         }
487                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
488                         cxrow->setTab(i, lf + rg);
489                         rg = ws_[i] - ww + colsep();
490                         if (cxrow == row_.begin())
491                                 width += ws_[i] + colsep();
492                 }
493                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
494         }
495 */
496         metricsMarkers2(dim);
497         // Cache the inset dimension.
498         setDimCache(mi, dim);
499 }
500
501
502 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
503 {
504         drawWithMargin(pi, x, y, 1, 1);
505 }
506
507
508 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
509         int lmargin, int rmargin) const
510 {
511         Dimension const dim = dimension(*pi.base.bv);
512         BufferView const & bv = *pi.base.bv;
513
514         for (idx_type idx = 0; idx < nargs(); ++idx)
515                 cell(idx).draw(pi, x + lmargin + cellXOffset(bv, idx),
516                         y + cellYOffset(idx));
517
518         for (row_type row = 0; row <= nrows(); ++row)
519                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
520                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
521                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
522                         pi.pain.line(x + lmargin + 1, yy,
523                                      x + dim.width() - rmargin - 1, yy,
524                                      Color_foreground);
525                 }
526
527         for (col_type col = 0; col <= ncols(); ++col)
528                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
529                         int xx = x + lmargin + colinfo_[col].offset_
530                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
531                         pi.pain.line(xx, y - dim.ascent() + 1,
532                                      xx, y + dim.descent() - 1,
533                                      Color_foreground);
534                 }
535         drawMarkers2(pi, x, y);
536 }
537
538
539 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
540 {
541         // let the cells adjust themselves
542         //InsetMathNest::metrics(mi);
543         for (idx_type i = 0; i < nargs(); ++i)
544                 cell(i).metricsT(mi, dim);
545
546         // compute absolute sizes of vertical structure
547         for (row_type row = 0; row < nrows(); ++row) {
548                 int asc  = 0;
549                 int desc = 0;
550                 for (col_type col = 0; col < ncols(); ++col) {
551                         //MathData const & c = cell(index(row, col));
552                         // FIXME: BROKEN!
553                         Dimension dimc;
554                         asc  = max(asc,  dimc.ascent());
555                         desc = max(desc, dimc.descent());
556                 }
557                 rowinfo_[row].ascent_  = asc;
558                 rowinfo_[row].descent_ = desc;
559         }
560         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
561         rowinfo_[nrows()].ascent_  = 0;
562         rowinfo_[nrows()].descent_ = 0;
563
564         // compute vertical offsets
565         rowinfo_[0].offset_ = 0;
566         for (row_type row = 1; row <= nrows(); ++row) {
567                 rowinfo_[row].offset_  =
568                         rowinfo_[row - 1].offset_  +
569                         rowinfo_[row - 1].descent_ +
570                         //rowinfo_[row - 1].skipPixels(mi) +
571                         1 + //rowsep() +
572                         //rowinfo_[row].lines_ * hlinesep() +
573                         rowinfo_[row].ascent_;
574         }
575
576         // adjust vertical offset
577         int h = 0;
578         switch (v_align_) {
579                 case 't':
580                         h = 0;
581                         break;
582                 case 'b':
583                         h = rowinfo_[nrows() - 1].offset_;
584                         break;
585                 default:
586                         h = rowinfo_[nrows() - 1].offset_ / 2;
587         }
588         for (row_type row = 0; row <= nrows(); ++row)
589                 rowinfo_[row].offset_ -= h;
590
591
592         // compute absolute sizes of horizontal structure
593         for (col_type col = 0; col < ncols(); ++col) {
594                 int wid = 0;
595                 for (row_type row = 0; row < nrows(); ++row) {
596                         // FIXME: BROKEN!
597                         //wid = max(wid, cell(index(row, col)).width());
598                 }
599                 colinfo_[col].width_ = wid;
600         }
601         colinfo_[ncols()].width_  = 0;
602
603         // compute horizontal offsets
604         colinfo_[0].offset_ = border();
605         for (col_type col = 1; col <= ncols(); ++col) {
606                 colinfo_[col].offset_ =
607                         colinfo_[col - 1].offset_ +
608                         colinfo_[col - 1].width_ +
609                         colinfo_[col - 1].skip_ +
610                         1 ; //colsep() +
611                         //colinfo_[col].lines_ * vlinesep();
612         }
613
614
615         dim.wid  =  colinfo_[ncols() - 1].offset_
616                        + colinfo_[ncols() - 1].width_
617                  //+ vlinesep() * colinfo_[ncols()].lines_
618                        + 2;
619
620         dim.asc  = -rowinfo_[0].offset_
621                        + rowinfo_[0].ascent_
622                  //+ hlinesep() * rowinfo_[0].lines_
623                        + 1;
624
625         dim.des  =  rowinfo_[nrows() - 1].offset_
626                        + rowinfo_[nrows() - 1].descent_
627                  //+ hlinesep() * rowinfo_[nrows()].lines_
628                        + 1;
629 }
630
631
632 void InsetMathGrid::drawT(TextPainter & /*pain*/, int /*x*/, int /*y*/) const
633 {
634 //      for (idx_type idx = 0; idx < nargs(); ++idx)
635 //              cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
636 }
637
638
639 void InsetMathGrid::updateBuffer(ParIterator const & it, UpdateType utype)
640 {
641         // pass down
642         for (idx_type idx = 0; idx < nargs(); ++idx)
643                 cell(idx).updateBuffer(it, utype);
644 }
645
646
647 docstring InsetMathGrid::eolString(row_type row, bool fragile, bool latex,
648                 bool last_eoln) const
649 {
650         docstring eol;
651
652         if (!rowinfo_[row].crskip_.zero())
653                 eol += '[' + from_utf8(rowinfo_[row].crskip_.asLatexString()) + ']';
654         else if(!rowinfo_[row].allow_newpage_)
655                 eol += '*';
656
657         // make sure an upcoming '[' does not break anything
658         if (row + 1 < nrows()) {
659                 MathData const & c = cell(index(row + 1, 0));
660                 if (c.size() && c.front()->getChar() == '[')
661                         //eol += "[0pt]";
662                         eol += "{}";
663         }
664
665         // only add \\ if necessary
666         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !last_eoln))
667                 return docstring();
668
669         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
670 }
671
672
673 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
674 {
675         if (col + 1 == lastcol)
676                 return docstring();
677         return from_ascii(" & ");
678 }
679
680
681 void InsetMathGrid::addRow(row_type row)
682 {
683         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
684         cells_.insert
685                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathData());
686         cellinfo_.insert
687                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
688 }
689
690
691 void InsetMathGrid::appendRow()
692 {
693         rowinfo_.push_back(RowInfo());
694         //cells_.insert(cells_.end(), ncols(), MathData());
695         for (col_type col = 0; col < ncols(); ++col) {
696                 cells_.push_back(cells_type::value_type());
697                 cellinfo_.push_back(CellInfo());
698         }
699 }
700
701
702 void InsetMathGrid::delRow(row_type row)
703 {
704         if (nrows() == 1)
705                 return;
706
707         cells_type::iterator it = cells_.begin() + row * ncols();
708         cells_.erase(it, it + ncols());
709
710         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
711         cellinfo_.erase(jt, jt + ncols());
712
713         rowinfo_.erase(rowinfo_.begin() + row);
714 }
715
716
717 void InsetMathGrid::copyRow(row_type row)
718 {
719         addRow(row);
720         for (col_type col = 0; col < ncols(); ++col)
721                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
722 }
723
724
725 void InsetMathGrid::swapRow(row_type row)
726 {
727         if (nrows() == 1)
728                 return;
729         if (row + 1 == nrows())
730                 --row;
731         for (col_type col = 0; col < ncols(); ++col)
732                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
733 }
734
735
736 void InsetMathGrid::addCol(col_type newcol)
737 {
738         const col_type nc = ncols();
739         const row_type nr = nrows();
740         cells_type new_cells((nc + 1) * nr);
741         vector<CellInfo> new_cellinfo((nc + 1) * nr);
742
743         for (row_type row = 0; row < nr; ++row)
744                 for (col_type col = 0; col < nc; ++col) {
745                         new_cells[row * (nc + 1) + col + (col >= newcol)]
746                                 = cells_[row * nc + col];
747                         new_cellinfo[row * (nc + 1) + col + (col >= newcol)]
748                                 = cellinfo_[row * nc + col];
749                 }
750         swap(cells_, new_cells);
751         swap(cellinfo_, new_cellinfo);
752
753         ColInfo inf;
754         inf.skip_  = defaultColSpace(newcol);
755         inf.align_ = defaultColAlign(newcol);
756         colinfo_.insert(colinfo_.begin() + newcol, inf);
757 }
758
759
760 void InsetMathGrid::delCol(col_type col)
761 {
762         if (ncols() == 1)
763                 return;
764
765         cells_type tmpcells;
766         vector<CellInfo> tmpcellinfo;
767         for (col_type i = 0; i < nargs(); ++i)
768                 if (i % ncols() != col) {
769                         tmpcells.push_back(cells_[i]);
770                         tmpcellinfo.push_back(cellinfo_[i]);
771                 }
772         swap(cells_, tmpcells);
773         swap(cellinfo_, tmpcellinfo);
774
775         colinfo_.erase(colinfo_.begin() + col);
776 }
777
778
779 void InsetMathGrid::copyCol(col_type col)
780 {
781         addCol(col+1);
782         for (row_type row = 0; row < nrows(); ++row)
783                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
784 }
785
786
787 void InsetMathGrid::swapCol(col_type col)
788 {
789         if (ncols() == 1)
790                 return;
791         if (col + 1 == ncols())
792                 --col;
793         for (row_type row = 0; row < nrows(); ++row)
794                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
795 }
796
797
798 int InsetMathGrid::cellXOffset(BufferView const & bv, idx_type idx) const
799 {
800         col_type c = col(idx);
801         int x = colinfo_[c].offset_;
802         char align = colinfo_[c].align_;
803         Dimension const & celldim = cell(idx).dimension(bv);
804         if (align == 'r' || align == 'R')
805                 x += colinfo_[c].width_ - celldim.wid;
806         if (align == 'c' || align == 'C')
807                 x += (colinfo_[c].width_ - celldim.wid) / 2;
808         return x;
809 }
810
811
812 int InsetMathGrid::cellYOffset(idx_type idx) const
813 {
814         return rowinfo_[row(idx)].offset_;
815 }
816
817
818 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
819 {
820         if (up) {
821                 if (cur.row() == 0)
822                         return false;
823                 cur.idx() -= ncols();
824         } else {
825                 if (cur.row() + 1 >= nrows())
826                         return false;
827                 cur.idx() += ncols();
828         }
829         cur.pos() = cur.cell().x2pos(&cur.bv(), cur.x_target() - cur.cell().xo(cur.bv()));
830         return true;
831 }
832
833
834 bool InsetMathGrid::idxBackward(Cursor & cur) const
835 {
836         // leave matrix if at the front edge
837         if (cur.col() == 0)
838                 return false;
839         --cur.idx();
840         cur.pos() = cur.lastpos();
841         return true;
842 }
843
844
845 bool InsetMathGrid::idxForward(Cursor & cur) const
846 {
847         // leave matrix if at the back edge
848         if (cur.col() + 1 == ncols())
849                 return false;
850         ++cur.idx();
851         cur.pos() = 0;
852         return true;
853 }
854
855
856 bool InsetMathGrid::idxFirst(Cursor & cur) const
857 {
858         switch (v_align_) {
859                 case 't':
860                         cur.idx() = 0;
861                         break;
862                 case 'b':
863                         cur.idx() = (nrows() - 1) * ncols();
864                         break;
865                 default:
866                         cur.idx() = ((nrows() - 1) / 2) * ncols();
867         }
868         cur.pos() = 0;
869         return true;
870 }
871
872
873 bool InsetMathGrid::idxLast(Cursor & cur) const
874 {
875         switch (v_align_) {
876                 case 't':
877                         cur.idx() = ncols() - 1;
878                         break;
879                 case 'b':
880                         cur.idx() = nargs() - 1;
881                         break;
882                 default:
883                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
884         }
885         cur.pos() = cur.lastpos();
886         return true;
887 }
888
889
890 bool InsetMathGrid::idxDelete(idx_type & idx)
891 {
892         // nothing to do if we have just one row
893         if (nrows() == 1)
894                 return false;
895
896         // nothing to do if we are in the middle of the last row of the inset
897         if (idx + ncols() > nargs())
898                 return false;
899
900         // try to delete entire sequence of ncols() empty cells if possible
901         for (idx_type i = idx; i < idx + ncols(); ++i)
902                 if (cell(i).size())
903                         return false;
904
905         // move cells if necessary
906         for (idx_type i = index(row(idx), 0); i < idx; ++i)
907                 swap(cell(i), cell(i + ncols()));
908
909         delRow(row(idx));
910
911         if (idx >= nargs())
912                 idx = nargs() - 1;
913
914         // undo effect of Ctrl-Tab (i.e. pull next cell)
915         //if (idx + 1 != nargs())
916         //      cell(idx).swap(cell(idx + 1));
917
918         // we handled the event..
919         return true;
920 }
921
922
923 // reimplement old behaviour when pressing Delete in the last position
924 // of a cell
925 void InsetMathGrid::idxGlue(idx_type idx)
926 {
927         col_type c = col(idx);
928         if (c + 1 == ncols()) {
929                 if (row(idx) + 1 != nrows()) {
930                         for (col_type cc = 0; cc < ncols(); ++cc)
931                                 cell(idx).append(cell(idx + cc + 1));
932                         delRow(row(idx) + 1);
933                 }
934         } else {
935                 cell(idx).append(cell(idx + 1));
936                 for (col_type cc = c + 2; cc < ncols(); ++cc)
937                         cell(idx - c + cc - 1) = cell(idx - c + cc);
938                 cell(idx - c + ncols() - 1).clear();
939         }
940 }
941
942
943 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
944 {
945         return rowinfo_[row];
946 }
947
948
949 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
950 {
951         return rowinfo_[row];
952 }
953
954
955 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
956 {
957         row_type const ri = row(idx);
958         row_type const r1 = min(row(from), row(to));
959         row_type const r2 = max(row(from), row(to));
960         col_type const ci = col(idx);
961         col_type const c1 = min(col(from), col(to));
962         col_type const c2 = max(col(from), col(to));
963         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
964 }
965
966
967
968 void InsetMathGrid::normalize(NormalStream & os) const
969 {
970         os << "[grid ";
971         for (row_type row = 0; row < nrows(); ++row) {
972                 os << "[row ";
973                 for (col_type col = 0; col < ncols(); ++col)
974                         os << "[cell " << cell(index(row, col)) << ']';
975                 os << ']';
976         }
977         os << ']';
978 }
979
980
981 void InsetMathGrid::mathmlize(MathStream & os) const
982 {
983         bool const havetable = nrows() > 1 || ncols() > 1;
984         if (havetable)
985                 os << MTag("mtable");
986         char const * const celltag = havetable ? "mtd" : "mrow";
987         for (row_type row = 0; row < nrows(); ++row) {
988                 if (havetable)
989                         os << MTag("mtr");;
990                 for (col_type col = 0; col < ncols(); ++col) {
991                         os << MTag(celltag);
992                         os << cell(index(row, col));
993                         os << ETag(celltag);
994                 }
995                 if (havetable)
996                         os << ETag("mtr");;
997         }
998         if (havetable)
999                 os << ETag("mtable");
1000 }
1001
1002
1003 // FIXME XHTML
1004 // We need to do something about alignment here.
1005 void InsetMathGrid::htmlize(HtmlStream & os, string attrib) const
1006 {
1007         bool const havetable = nrows() > 1 || ncols() > 1;
1008         if (!havetable) {
1009                 os << cell(index(0, 0));
1010                 return;
1011         }
1012         os << MTag("table", attrib);
1013         for (row_type row = 0; row < nrows(); ++row) {
1014                 os << MTag("tr");;
1015                 for (col_type col = 0; col < ncols(); ++col) {
1016                         os << MTag("td");
1017                         os << cell(index(row, col));
1018                         os << ETag("td");
1019                 }
1020                 os << ETag("tr");;
1021         }
1022         os << ETag("table");
1023 }
1024
1025
1026 void InsetMathGrid::htmlize(HtmlStream & os) const
1027 {
1028         htmlize(os, "class='mathtable'");
1029 }
1030
1031
1032 void InsetMathGrid::write(WriteStream & os) const
1033 {
1034         write(os, 0, 0, nrows(), ncols());
1035 }
1036
1037 void InsetMathGrid::write(WriteStream & os,
1038                           row_type beg_row, col_type beg_col,
1039                           row_type end_row, col_type end_col) const
1040 {
1041         MathEnsurer ensurer(os, false);
1042         docstring eol;
1043         for (row_type row = beg_row; row < end_row; ++row) {
1044                 os << verboseHLine(rowinfo_[row].lines_);
1045                 // don't write & and empty cells at end of line,
1046                 // unless there are vertical lines
1047                 col_type lastcol = 0;
1048                 bool emptyline = true;
1049                 bool last_eoln = true;
1050                 for (col_type col = beg_col; col < end_col; ++col) {
1051                         bool const empty_cell = cell(index(row, col)).empty();
1052                         if (!empty_cell)
1053                                 last_eoln = false;
1054                         if (!empty_cell || colinfo_[col + 1].lines_) {
1055                                 lastcol = col + 1;
1056                                 emptyline = false;
1057                         }
1058                 }
1059                 for (col_type col = beg_col; col < lastcol; ++col) {
1060                         os << cell(index(row, col));
1061                         if (os.pendingBrace())
1062                                 ModeSpecifier specifier(os, TEXT_MODE);
1063                         os << eocString(col, lastcol);
1064                 }
1065                 eol = eolString(row, os.fragile(), os.latex(), last_eoln);
1066                 os << eol;
1067                 // append newline only if line wasn't completely empty
1068                 // and the formula is not written on a single line
1069                 bool const empty = emptyline && eol.empty();
1070                 if (!empty && nrows() > 1)
1071                         os << "\n";
1072         }
1073         // @TODO use end_row instead of nrows() ?
1074         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
1075         if (!s.empty()) {
1076                 if (eol.empty()) {
1077                         if (os.fragile())
1078                                 os << "\\protect";
1079                         os << "\\\\";
1080                 }
1081                 os << s;
1082         }
1083 }
1084
1085
1086 int InsetMathGrid::colsep() const
1087 {
1088         return 6;
1089 }
1090
1091
1092 int InsetMathGrid::rowsep() const
1093 {
1094         return 6;
1095 }
1096
1097
1098 int InsetMathGrid::hlinesep() const
1099 {
1100         return 3;
1101 }
1102
1103
1104 int InsetMathGrid::vlinesep() const
1105 {
1106         return 3;
1107 }
1108
1109
1110 int InsetMathGrid::border() const
1111 {
1112         return 1;
1113 }
1114
1115
1116 void InsetMathGrid::splitCell(Cursor & cur)
1117 {
1118         if (cur.idx() == cur.lastidx())
1119                 return;
1120         MathData ar = cur.cell();
1121         ar.erase(0, cur.pos());
1122         cur.cell().erase(cur.pos(), cur.lastpos());
1123         ++cur.idx();
1124         cur.pos() = 0;
1125         cur.cell().insert(0, ar);
1126 }
1127
1128
1129 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1130 {
1131         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1132
1133         Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
1134
1135         FuncCode const act = cmd.action();
1136         switch (act) {
1137
1138         // insert file functions
1139         case LFUN_LINE_DELETE:
1140                 cur.recordUndoInset();
1141                 //autocorrect_ = false;
1142                 //macroModeClose();
1143                 //if (selection_) {
1144                 //      selDel();
1145                 //      break;
1146                 //}
1147                 if (nrows() > 1)
1148                         delRow(cur.row());
1149                 if (cur.idx() > cur.lastidx())
1150                         cur.idx() = cur.lastidx();
1151                 if (cur.pos() > cur.lastpos())
1152                         cur.pos() = cur.lastpos();
1153                 break;
1154
1155         case LFUN_CELL_SPLIT:
1156                 cur.recordUndo();
1157                 splitCell(cur);
1158                 break;
1159
1160         case LFUN_CELL_BACKWARD:
1161                 // See below.
1162                 cur.setSelection(false);
1163                 if (!idxPrev(cur)) {
1164                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1165                         cur.undispatched();
1166                 }
1167                 break;
1168
1169         case LFUN_CELL_FORWARD:
1170                 // Can't handle selection by additional 'shift' as this is
1171                 // hard bound to LFUN_CELL_BACKWARD
1172                 cur.setSelection(false);
1173                 if (!idxNext(cur)) {
1174                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1175                         cur.undispatched();
1176                 }
1177                 break;
1178
1179         case LFUN_NEWLINE_INSERT: {
1180                 cur.recordUndoInset();
1181                 row_type const r = cur.row();
1182                 addRow(r);
1183
1184                 // split line
1185                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1186                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1187
1188                 // split cell
1189                 splitCell(cur);
1190                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1191                 if (cur.idx() > 0)
1192                         --cur.idx();
1193                 cur.pos() = cur.lastpos();
1194
1195                 //mathcursor->normalize();
1196                 //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1197                 break;
1198         }
1199
1200         case LFUN_INSET_MODIFY: {
1201                 cur.recordUndoInset();
1202                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1203                 istringstream is(to_utf8(cmd.argument()));
1204                 string s;
1205                 is >> s;
1206                 if (s != "tabular") {
1207                         InsetMathNest::doDispatch(cur, cmd);
1208                         return;
1209                 }
1210                 is >> s;
1211                 if (s == "valign-top")
1212                         setVerticalAlignment('t');
1213                 else if (s == "valign-middle")
1214                         setVerticalAlignment('c');
1215                 else if (s == "valign-bottom")
1216                         setVerticalAlignment('b');
1217                 else if (s == "align-left")
1218                         setHorizontalAlignment('l', cur.col());
1219                 else if (s == "align-right")
1220                         setHorizontalAlignment('r', cur.col());
1221                 else if (s == "align-center")
1222                         setHorizontalAlignment('c', cur.col());
1223                 else if (s == "append-row")
1224                         for (int i = 0, n = extractInt(is); i < n; ++i)
1225                                 addRow(cur.row());
1226                 else if (s == "delete-row") {
1227                         cur.clearSelection(); // bug 4323
1228                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1229                                 delRow(cur.row());
1230                                 if (cur.idx() >= nargs())
1231                                         cur.idx() -= ncols();
1232                         }
1233                         cur.pos() = 0; // trick, see below
1234                 }
1235                 else if (s == "copy-row") {
1236                         // Here (as later) we save the cursor col/row
1237                         // in order to restore it after operation.
1238                         row_type const r = cur.row();
1239                         col_type const c = cur.col();
1240                         for (int i = 0, n = extractInt(is); i < n; ++i)
1241                                 copyRow(cur.row());
1242                         cur.idx() = index(r, c);
1243                 }
1244                 else if (s == "swap-row") {
1245                         swapRow(cur.row());
1246                         // Trick to suppress same-idx-means-different-cell
1247                         // assertion crash:
1248                         cur.pos() = 0;
1249                 }
1250                 else if (s == "add-hline-above")
1251                         rowinfo_[cur.row()].lines_++;
1252                 else if (s == "add-hline-below")
1253                         rowinfo_[cur.row()+1].lines_++;
1254                 else if (s == "delete-hline-above")
1255                         rowinfo_[cur.row()].lines_--;
1256                 else if (s == "delete-hline-below")
1257                         rowinfo_[cur.row()+1].lines_--;
1258                 else if (s == "append-column") {
1259                         row_type const r = cur.row();
1260                         col_type const c = cur.col();
1261                         for (int i = 0, n = extractInt(is); i < n; ++i)
1262                                 addCol(cur.col() + 1);
1263                         cur.idx() = index(r, c);
1264                 }
1265                 else if (s == "delete-column") {
1266                         cur.clearSelection(); // bug 4323
1267                         row_type const r = cur.row();
1268                         col_type const c = cur.col();
1269                         for (int i = 0, n = extractInt(is); i < n; ++i)
1270                                 delCol(col(cur.idx()));
1271                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1272                         cur.pos() = 0; // trick, see above
1273                 }
1274                 else if (s == "copy-column") {
1275                         row_type const r = cur.row();
1276                         col_type const c = cur.col();
1277                         copyCol(cur.col());
1278                         cur.idx() = index(r, c);
1279                 }
1280                 else if (s == "swap-column") {
1281                         swapCol(cur.col());
1282                         cur.pos() = 0; // trick, see above
1283                 }
1284                 else if (s == "add-vline-left") {
1285                         colinfo_[cur.col()].lines_++;
1286                         if (!colinfo_[cur.col()].special_.empty())
1287                                 colinfo_[cur.col()].special_ += '|';
1288                 }
1289                 else if (s == "add-vline-right") {
1290                         colinfo_[cur.col()+1].lines_++;
1291                         if (!colinfo_[cur.col()+1].special_.empty())
1292                                 colinfo_[cur.col()+1].special_.insert(0, 1, '|');
1293                 }
1294                 else if (s == "delete-vline-left") {
1295                         colinfo_[cur.col()].lines_--;
1296                         docstring & special = colinfo_[cur.col()].special_;
1297                         if (!special.empty()) {
1298                                 docstring::size_type i = special.rfind('|');
1299                                 LASSERT(i != docstring::npos, /**/);
1300                                 special.erase(i, 1);
1301                         }
1302                 }
1303                 else if (s == "delete-vline-right") {
1304                         colinfo_[cur.col()+1].lines_--;
1305                         docstring & special = colinfo_[cur.col()+1].special_;
1306                         if (!special.empty()) {
1307                                 docstring::size_type i = special.find('|');
1308                                 LASSERT(i != docstring::npos, /**/);
1309                                 special.erase(i, 1);
1310                         }
1311                 }
1312                 else {
1313                         cur.undispatched();
1314                         break;
1315                 }
1316                 // perhaps this should be FINISHED_BACKWARD -- just for clarity?
1317                 //lyxerr << "returning FINISHED_LEFT" << endl;
1318                 break;
1319         }
1320
1321         case LFUN_CLIPBOARD_PASTE:
1322                 parseflg |= Parse::VERBATIM;
1323                 // fall through
1324         case LFUN_PASTE: {
1325                 if (cur.currentMode() <= TEXT_MODE)
1326                         parseflg |= Parse::TEXTMODE;
1327                 cur.message(_("Paste"));
1328                 cap::replaceSelection(cur);
1329                 docstring topaste;
1330                 if (cmd.argument().empty() && !theClipboard().isInternal())
1331                         topaste = theClipboard().getAsText();
1332                 else {
1333                         idocstringstream is(cmd.argument());
1334                         int n = 0;
1335                         is >> n;
1336                         topaste = cap::selection(n);
1337                 }
1338                 InsetMathGrid grid(buffer_, 1, 1);
1339                 if (!topaste.empty())
1340                         if ((topaste.size() == 1 && topaste.at(0) < 0x80)
1341                             || !mathed_parse_normal(grid, topaste, parseflg)) {
1342                                 resetGrid(grid);
1343                                 mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
1344                         }
1345
1346                 if (grid.nargs() == 1) {
1347                         // single cell/part of cell
1348                         cur.recordUndo();
1349                         cur.cell().insert(cur.pos(), grid.cell(0));
1350                         cur.pos() += grid.cell(0).size();
1351                 } else {
1352                         // multiple cells
1353                         cur.recordUndoInset();
1354                         col_type const numcols =
1355                                 min(grid.ncols(), ncols() - col(cur.idx()));
1356                         row_type const numrows =
1357                                 min(grid.nrows(), nrows() - cur.row());
1358                         for (row_type r = 0; r < numrows; ++r) {
1359                                 for (col_type c = 0; c < numcols; ++c) {
1360                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1361                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1362                                 }
1363                                 // append the left over horizontal cells to the last column
1364                                 idx_type i = index(r + cur.row(), ncols() - 1);
1365                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1366                                         cell(i).append(grid.cell(grid.index(r, c)));
1367                         }
1368                         // append the left over vertical cells to the last _cell_
1369                         idx_type i = nargs() - 1;
1370                         for (row_type r = numrows; r < grid.nrows(); ++r)
1371                                 for (col_type c = 0; c < grid.ncols(); ++c)
1372                                         cell(i).append(grid.cell(grid.index(r, c)));
1373                 }
1374                 cur.clearSelection(); // bug 393
1375                 // FIXME audit setBuffer calls
1376                 cur.inset().setBuffer(*buffer_);
1377                 cur.forceBufferUpdate();
1378                 cur.finishUndo();
1379                 break;
1380         }
1381
1382         case LFUN_LINE_BEGIN_SELECT:
1383         case LFUN_LINE_BEGIN:
1384         case LFUN_WORD_BACKWARD_SELECT:
1385         case LFUN_WORD_BACKWARD:
1386         case LFUN_WORD_LEFT_SELECT:
1387         case LFUN_WORD_LEFT:
1388                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1389                                 act == LFUN_WORD_LEFT_SELECT ||
1390                                 act == LFUN_LINE_BEGIN_SELECT);
1391                 cur.macroModeClose();
1392                 if (cur.pos() != 0) {
1393                         cur.pos() = 0;
1394                 } else if (cur.idx() % cur.ncols() != 0) {
1395                         cur.idx() -= cur.idx() % cur.ncols();
1396                         cur.pos() = 0;
1397                 } else if (cur.idx() != 0) {
1398                         cur.idx() = 0;
1399                         cur.pos() = 0;
1400                 } else {
1401                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1402                         cur.undispatched();
1403                 }
1404                 break;
1405
1406         case LFUN_WORD_FORWARD_SELECT:
1407         case LFUN_WORD_FORWARD:
1408         case LFUN_WORD_RIGHT_SELECT:
1409         case LFUN_WORD_RIGHT:
1410         case LFUN_LINE_END_SELECT:
1411         case LFUN_LINE_END:
1412                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1413                                 act == LFUN_WORD_RIGHT_SELECT ||
1414                                 act == LFUN_LINE_END_SELECT);
1415                 cur.macroModeClose();
1416                 cur.clearTargetX();
1417                 if (cur.pos() != cur.lastpos()) {
1418                         cur.pos() = cur.lastpos();
1419                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1420                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1421                         cur.pos() = cur.lastpos();
1422                 } else if (cur.idx() != cur.lastidx()) {
1423                         cur.idx() = cur.lastidx();
1424                         cur.pos() = cur.lastpos();
1425                 } else {
1426                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1427                         cur.undispatched();
1428                 }
1429                 break;
1430
1431         default:
1432                 InsetMathNest::doDispatch(cur, cmd);
1433         }
1434 }
1435
1436
1437 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1438                 FuncStatus & status) const
1439 {
1440         switch (cmd.action()) {
1441         case LFUN_INSET_MODIFY: {
1442                 istringstream is(to_utf8(cmd.argument()));
1443                 string s;
1444                 is >> s;
1445                 if (s != "tabular") {
1446                         // We only now about table actions here.
1447                         break;
1448                 }
1449                 if (&cur.inset() != this) {
1450                         // Table actions requires that the cursor is _inside_ the
1451                         // table.
1452                         status.setEnabled(false);
1453                         status.message(from_utf8(N_("Cursor not in table")));
1454                         return true;
1455                 }
1456                 is >> s;
1457                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1458                         status.setEnabled(false);
1459                         status.message(from_utf8(N_("Only one row")));
1460                         return true;
1461                 }
1462                 if (ncols() <= 1 &&
1463                     (s == "delete-column" || s == "swap-column")) {
1464                         status.setEnabled(false);
1465                         status.message(from_utf8(N_("Only one column")));
1466                         return true;
1467                 }
1468                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1469                      s == "delete-hline-above") ||
1470                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1471                      s == "delete-hline-below")) {
1472                         status.setEnabled(false);
1473                         status.message(from_utf8(N_("No hline to delete")));
1474                         return true;
1475                 }
1476
1477                 if ((colinfo_[cur.col()].lines_ == 0 &&
1478                      s == "delete-vline-left") ||
1479                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1480                      s == "delete-vline-right")) {
1481                         status.setEnabled(false);
1482                         status.message(from_utf8(N_("No vline to delete")));
1483                         return true;
1484                 }
1485                 if (s == "valign-top" || s == "valign-middle" ||
1486                     s == "valign-bottom" || s == "align-left" ||
1487                     s == "align-right" || s == "align-center") {
1488                         status.setEnabled(true);
1489                         char const ha = horizontalAlignment(cur.col());
1490                         char const va = verticalAlignment();
1491                         status.setOnOff((s == "align-left" && ha == 'l')
1492                                         || (s == "align-right"   && ha == 'r')
1493                                         || (s == "align-center"  && ha == 'c')
1494                                         || (s == "valign-top"    && va == 't')
1495                                         || (s == "valign-bottom" && va == 'b')
1496                                         || (s == "valign-middle" && va == 'c'));
1497                         return true;
1498                 }
1499                 if (s == "append-row" || s == "delete-row" ||
1500                     s == "copy-row" || s == "swap-row" ||
1501                     s == "add-hline-above" || s == "add-hline-below" ||
1502                     s == "delete-hline-above" || s == "delete-hline-below" ||
1503                     s == "append-column" || s == "delete-column" ||
1504                     s == "copy-column" || s == "swap-column" ||
1505                     s == "add-vline-left" || s == "add-vline-right" ||
1506                     s == "delete-vline-left" || s == "delete-vline-right") {
1507                         status.setEnabled(true);
1508                 } else {
1509                         status.setEnabled(false);
1510                         status.message(bformat(
1511                                 from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1512                 }
1513
1514 #if 0
1515                 // FIXME: What did this code do?
1516                 // Please check whether it is still needed!
1517                 // should be more precise
1518                 if (v_align_ == '\0') {
1519                         status.enable(true);
1520                         break;
1521                 }
1522                 if (cmd.argument().empty()) {
1523                         status.enable(false);
1524                         break;
1525                 }
1526                 if (!contains("tcb", cmd.argument()[0])) {
1527                         status.enable(false);
1528                         break;
1529                 }
1530                 status.setOnOff(cmd.argument()[0] == v_align_);
1531                 status.setEnabled(true);
1532 #endif
1533                 return true;
1534         }
1535
1536         case LFUN_CELL_SPLIT:
1537                 status.setEnabled(true);
1538                 return true;
1539
1540         case LFUN_CELL_BACKWARD:
1541         case LFUN_CELL_FORWARD:
1542                 status.setEnabled(true);
1543                 return true;
1544
1545         default:
1546                 break;
1547         }
1548         return InsetMathNest::getStatus(cur, cmd, status);
1549 }
1550
1551
1552 } // namespace lyx