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