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