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