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