]> git.lyx.org Git - lyx.git/blob - src/mathed/math_gridinset.C
fix a few small bugs
[lyx.git] / src / mathed / math_gridinset.C
1 /**
2  * \file math_gridinset.C
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 "math_gridinset.h"
14 #include "math_data.h"
15 #include "math_mathmlstream.h"
16 #include "math_streamstr.h"
17
18 #include "BufferView.h"
19 #include "CutAndPaste.h"
20 #include "FuncStatus.h"
21 #include "LColor.h"
22 #include "cursor.h"
23 #include "debug.h"
24 #include "funcrequest.h"
25
26 #include "frontends/Painter.h"
27
28 #include "support/std_sstream.h"
29
30 #include "insets/mailinset.h"
31
32 using std::endl;
33 using std::max;
34 using std::min;
35 using std::swap;
36
37 using std::string;
38 using std::auto_ptr;
39 using std::istream;
40 using std::istringstream;
41 using std::ostringstream;
42 using std::vector;
43
44
45 class GridInsetMailer : public MailInset {
46 public:
47         GridInsetMailer(MathGridInset & inset) : inset_(inset) {}
48         ///
49         virtual string const & name() const
50         {
51                 static string const theName = "tabular";
52                 return theName;
53         }
54         ///
55         virtual string const inset2string(Buffer const &) const
56         {
57                 ostringstream data;
58                 //data << name() << " active_cell " << inset.getActCell() << '\n';
59                 data << name() << " active_cell " << 0 << '\n';
60                 WriteStream ws(data);
61                 inset_.write(ws);
62                 return data.str();
63         }
64
65 protected:
66         InsetBase & inset() const { return inset_; }
67         MathGridInset & inset_;
68 };
69
70
71 void mathed_parse_normal(MathGridInset &, string const & argument);
72
73 namespace {
74
75 string verboseHLine(int n)
76 {
77         string res;
78         for (int i = 0; i < n; ++i)
79                 res += "\\hline";
80         if (n)
81                 res += ' ';
82         return res;
83 }
84
85
86 int extractInt(istream & is)
87 {
88         int num = 1;
89         is >> num;
90         return (num == 0) ? 1 : num;
91 }
92
93 }
94
95
96 //////////////////////////////////////////////////////////////
97
98
99 MathGridInset::CellInfo::CellInfo()
100         : dummy_(false)
101 {}
102
103
104
105
106 //////////////////////////////////////////////////////////////
107
108
109 MathGridInset::RowInfo::RowInfo()
110         : lines_(0), skip_(0)
111 {}
112
113
114
115 int MathGridInset::RowInfo::skipPixels() const
116 {
117         return crskip_.inBP();
118 }
119
120
121
122 //////////////////////////////////////////////////////////////
123
124
125 MathGridInset::ColInfo::ColInfo()
126         : align_('c'), leftline_(false), rightline_(false), lines_(0)
127 {}
128
129
130 //////////////////////////////////////////////////////////////
131
132
133 MathGridInset::MathGridInset(char v, string const & h)
134         : MathNestInset(guessColumns(h)),
135           rowinfo_(2),
136           colinfo_(guessColumns(h) + 1),
137           cellinfo_(1 * guessColumns(h))
138 {
139         setDefaults();
140         valign(v);
141         halign(h);
142         //lyxerr << "created grid with " << ncols() << " columns" << endl;
143 }
144
145
146 MathGridInset::MathGridInset()
147         : MathNestInset(1),
148           rowinfo_(1 + 1),
149                 colinfo_(1 + 1),
150                 cellinfo_(1),
151                 v_align_('c')
152 {
153         setDefaults();
154 }
155
156
157 MathGridInset::MathGridInset(col_type m, row_type n)
158         : MathNestInset(m * n),
159           rowinfo_(n + 1),
160                 colinfo_(m + 1),
161                 cellinfo_(m * n),
162                 v_align_('c')
163 {
164         setDefaults();
165 }
166
167
168 MathGridInset::MathGridInset(col_type m, row_type n, char v, string const & h)
169         : MathNestInset(m * n),
170           rowinfo_(n + 1),
171           colinfo_(m + 1),
172                 cellinfo_(m * n),
173                 v_align_(v)
174 {
175         setDefaults();
176         valign(v);
177         halign(h);
178 }
179
180
181 MathGridInset::~MathGridInset()
182 {
183         GridInsetMailer mailer(*this);
184         mailer.hideDialog();
185 }
186
187
188 auto_ptr<InsetBase> MathGridInset::clone() const
189 {
190         return auto_ptr<InsetBase>(new MathGridInset(*this));
191 }
192
193
194 MathInset::idx_type MathGridInset::index(row_type row, col_type col) const
195 {
196         return col + ncols() * row;
197 }
198
199
200 void MathGridInset::setDefaults()
201 {
202         if (ncols() <= 0)
203                 lyxerr << "positive number of columns expected" << endl;
204         //if (nrows() <= 0)
205         //      lyxerr << "positive number of rows expected" << endl;
206         for (col_type col = 0; col < ncols(); ++col) {
207                 colinfo_[col].align_ = defaultColAlign(col);
208                 colinfo_[col].skip_  = defaultColSpace(col);
209         }
210 }
211
212
213 void MathGridInset::halign(string const & hh)
214 {
215         col_type col = 0;
216         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it) {
217                 if (col >= ncols())
218                         break;
219                 char c = *it;
220                 if (c == '|') {
221                         colinfo_[col].lines_++;
222                 } else if (c == 'c' || c == 'l' || c == 'r') {
223                         colinfo_[col].align_ = c;
224                         ++col;
225                         colinfo_[col].lines_ = 0;
226                 } else {
227                         lyxerr << "unknown column separator: '" << c << "'" << endl;
228                 }
229         }
230
231 /*
232         col_type n = hh.size();
233         if (n > ncols())
234                 n = ncols();
235         for (col_type col = 0; col < n; ++col)
236                 colinfo_[col].align_ = hh[col];
237 */
238 }
239
240
241 MathGridInset::col_type MathGridInset::guessColumns(string const & hh) const
242 {
243         col_type col = 0;
244         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it)
245                 if (*it == 'c' || *it == 'l' || *it == 'r')
246                         ++col;
247         // let's have at least one column, even if we did not recognize its
248         // alignment
249         if (col == 0)
250                 col = 1;
251         return col;
252 }
253
254
255 void MathGridInset::halign(char h, col_type col)
256 {
257         colinfo_[col].align_ = h;
258 }
259
260
261 char MathGridInset::halign(col_type col) const
262 {
263         return colinfo_[col].align_;
264 }
265
266
267 string MathGridInset::halign() const
268 {
269         string res;
270         for (col_type col = 0; col < ncols(); ++col) {
271                 res += string(colinfo_[col].lines_, '|');
272                 res += colinfo_[col].align_;
273         }
274         return res + string(colinfo_[ncols()].lines_, '|');
275 }
276
277
278 void MathGridInset::valign(char c)
279 {
280         v_align_ = c;
281 }
282
283
284 char MathGridInset::valign() const
285 {
286         return v_align_;
287 }
288
289
290 MathGridInset::col_type MathGridInset::ncols() const
291 {
292         return colinfo_.size() - 1;
293 }
294
295
296 MathGridInset::row_type MathGridInset::nrows() const
297 {
298         return rowinfo_.size() - 1;
299 }
300
301
302 MathGridInset::col_type MathGridInset::col(idx_type idx) const
303 {
304         return idx % ncols();
305 }
306
307
308 MathGridInset::row_type MathGridInset::row(idx_type idx) const
309 {
310         return idx / ncols();
311 }
312
313
314 void MathGridInset::vcrskip(LyXLength const & crskip, row_type row)
315 {
316         rowinfo_[row].crskip_ = crskip;
317 }
318
319
320 LyXLength MathGridInset::vcrskip(row_type row) const
321 {
322         return rowinfo_[row].crskip_;
323 }
324
325
326 void MathGridInset::metrics(MetricsInfo & mi) const
327 {
328         // let the cells adjust themselves
329         MathNestInset::metrics(mi);
330
331         // compute absolute sizes of vertical structure
332         for (row_type row = 0; row < nrows(); ++row) {
333                 int asc  = 0;
334                 int desc = 0;
335                 for (col_type col = 0; col < ncols(); ++col) {
336                         MathArray const & c = cell(index(row, col));
337                         asc  = max(asc,  c.ascent());
338                         desc = max(desc, c.descent());
339                 }
340                 rowinfo_[row].ascent_  = asc;
341                 rowinfo_[row].descent_ = desc;
342         }
343         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
344         rowinfo_[nrows()].ascent_  = 0;
345         rowinfo_[nrows()].descent_ = 0;
346
347         // compute vertical offsets
348         rowinfo_[0].offset_ = 0;
349         for (row_type row = 1; row <= nrows(); ++row) {
350                 rowinfo_[row].offset_  =
351                         rowinfo_[row - 1].offset_  +
352                         rowinfo_[row - 1].descent_ +
353                         rowinfo_[row - 1].skipPixels() +
354                         rowsep() +
355                         rowinfo_[row].lines_ * hlinesep() +
356                         rowinfo_[row].ascent_;
357         }
358
359         // adjust vertical offset
360         int h = 0;
361         switch (v_align_) {
362                 case 't':
363                         h = 0;
364                         break;
365                 case 'b':
366                         h = rowinfo_[nrows() - 1].offset_;
367                         break;
368                 default:
369                         h = rowinfo_[nrows() - 1].offset_ / 2;
370         }
371         for (row_type row = 0; row <= nrows(); ++row)
372                 rowinfo_[row].offset_ -= h;
373
374
375         // compute absolute sizes of horizontal structure
376         for (col_type col = 0; col < ncols(); ++col) {
377                 int wid = 0;
378                 for (row_type row = 0; row < nrows(); ++row)
379                         wid = max(wid, cell(index(row, col)).width());
380                 colinfo_[col].width_ = wid;
381         }
382         colinfo_[ncols()].width_  = 0;
383
384         // compute horizontal offsets
385         colinfo_[0].offset_ = border();
386         for (col_type col = 1; col <= ncols(); ++col) {
387                 colinfo_[col].offset_ =
388                         colinfo_[col - 1].offset_ +
389                         colinfo_[col - 1].width_ +
390                         colinfo_[col - 1].skip_ +
391                         colsep() +
392                         colinfo_[col].lines_ * vlinesep();
393         }
394
395
396         dim_.wid   =   colinfo_[ncols() - 1].offset_
397                        + colinfo_[ncols() - 1].width_
398                  + vlinesep() * colinfo_[ncols()].lines_
399                        + border();
400
401         dim_.asc  = - rowinfo_[0].offset_
402                        + rowinfo_[0].ascent_
403                  + hlinesep() * rowinfo_[0].lines_
404                        + border();
405
406         dim_.des =   rowinfo_[nrows() - 1].offset_
407                        + rowinfo_[nrows() - 1].descent_
408                  + hlinesep() * rowinfo_[nrows()].lines_
409                        + border();
410
411
412 /*
413         // Increase ws_[i] for 'R' columns (except the first one)
414         for (int i = 1; i < nc_; ++i)
415                 if (align_[i] == 'R')
416                         ws_[i] += 10 * df_width;
417         // Increase ws_[i] for 'C' column
418         if (align_[0] == 'C')
419                 if (ws_[0] < 7 * workwidth / 8)
420                         ws_[0] = 7 * workwidth / 8;
421
422         // Adjust local tabs
423         width = colsep();
424         for (cxrow = row_.begin(); cxrow; ++cxrow) {
425                 int rg = COLSEP;
426                 int lf = 0;
427                 for (int i = 0; i < nc_; ++i) {
428                         bool isvoid = false;
429                         if (cxrow->getTab(i) <= 0) {
430                                 cxrow->setTab(i, df_width);
431                                 isvoid = true;
432                         }
433                         switch (align_[i]) {
434                         case 'l':
435                                 lf = 0;
436                                 break;
437                         case 'c':
438                                 lf = (ws_[i] - cxrow->getTab(i))/2;
439                                 break;
440                         case 'r':
441                         case 'R':
442                                 lf = ws_[i] - cxrow->getTab(i);
443                                 break;
444                         case 'C':
445                                 if (cxrow == row_.begin())
446                                         lf = 0;
447                                 else if (cxrow.is_last())
448                                         lf = ws_[i] - cxrow->getTab(i);
449                                 else
450                                         lf = (ws_[i] - cxrow->getTab(i))/2;
451                                 break;
452                         }
453                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
454                         cxrow->setTab(i, lf + rg);
455                         rg = ws_[i] - ww + colsep();
456                         if (cxrow == row_.begin())
457                                 width += ws_[i] + colsep();
458                 }
459                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
460         }
461 */
462         metricsMarkers2(dim_);
463 }
464
465
466 void MathGridInset::metrics(MetricsInfo & mi, Dimension & dim) const
467 {
468         metrics(mi);
469         dim = dim_;
470 }
471
472
473 void MathGridInset::draw(PainterInfo & pi, int x, int y) const
474 {
475         for (idx_type idx = 0; idx < nargs(); ++idx)
476                 cell(idx).draw(pi, x + cellXOffset(idx), y + cellYOffset(idx));
477
478         for (row_type row = 0; row <= nrows(); ++row)
479                 for (int i = 0; i < rowinfo_[row].lines_; ++i) {
480                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
481                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
482                         pi.pain.line(x + 1, yy,
483                                      x + dim_.width() - 1, yy,
484                                      LColor::foreground);
485                 }
486
487         for (col_type col = 0; col <= ncols(); ++col)
488                 for (int i = 0; i < colinfo_[col].lines_; ++i) {
489                         int xx = x + colinfo_[col].offset_
490                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
491                         pi.pain.line(xx, y - dim_.ascent() + 1,
492                                      xx, y + dim_.descent() - 1,
493                                      LColor::foreground);
494                 }
495         drawMarkers2(pi, x, y);
496 }
497
498
499 void MathGridInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
500 {
501         // let the cells adjust themselves
502         //MathNestInset::metrics(mi);
503         for (idx_type i = 0; i < nargs(); ++i)
504                 cell(i).metricsT(mi, dim);
505
506         // compute absolute sizes of vertical structure
507         for (row_type row = 0; row < nrows(); ++row) {
508                 int asc  = 0;
509                 int desc = 0;
510                 for (col_type col = 0; col < ncols(); ++col) {
511                         MathArray const & c = cell(index(row, col));
512                         asc  = max(asc,  c.ascent());
513                         desc = max(desc, c.descent());
514                 }
515                 rowinfo_[row].ascent_  = asc;
516                 rowinfo_[row].descent_ = desc;
517         }
518         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
519         rowinfo_[nrows()].ascent_  = 0;
520         rowinfo_[nrows()].descent_ = 0;
521
522         // compute vertical offsets
523         rowinfo_[0].offset_ = 0;
524         for (row_type row = 1; row <= nrows(); ++row) {
525                 rowinfo_[row].offset_  =
526                         rowinfo_[row - 1].offset_  +
527                         rowinfo_[row - 1].descent_ +
528                         //rowinfo_[row - 1].skipPixels() +
529                         1 + //rowsep() +
530                         //rowinfo_[row].lines_ * hlinesep() +
531                         rowinfo_[row].ascent_;
532         }
533
534         // adjust vertical offset
535         int h = 0;
536         switch (v_align_) {
537                 case 't':
538                         h = 0;
539                         break;
540                 case 'b':
541                         h = rowinfo_[nrows() - 1].offset_;
542                         break;
543                 default:
544                         h = rowinfo_[nrows() - 1].offset_ / 2;
545         }
546         for (row_type row = 0; row <= nrows(); ++row)
547                 rowinfo_[row].offset_ -= h;
548
549
550         // compute absolute sizes of horizontal structure
551         for (col_type col = 0; col < ncols(); ++col) {
552                 int wid = 0;
553                 for (row_type row = 0; row < nrows(); ++row)
554                         wid = max(wid, cell(index(row, col)).width());
555                 colinfo_[col].width_ = wid;
556         }
557         colinfo_[ncols()].width_  = 0;
558
559         // compute horizontal offsets
560         colinfo_[0].offset_ = border();
561         for (col_type col = 1; col <= ncols(); ++col) {
562                 colinfo_[col].offset_ =
563                         colinfo_[col - 1].offset_ +
564                         colinfo_[col - 1].width_ +
565                         colinfo_[col - 1].skip_ +
566                         1 ; //colsep() +
567                         //colinfo_[col].lines_ * vlinesep();
568         }
569
570
571         dim.wid  =  colinfo_[ncols() - 1].offset_
572                        + colinfo_[ncols() - 1].width_
573                  //+ vlinesep() * colinfo_[ncols()].lines_
574                        + 2;
575
576         dim.asc  = -rowinfo_[0].offset_
577                        + rowinfo_[0].ascent_
578                  //+ hlinesep() * rowinfo_[0].lines_
579                        + 1;
580
581         dim.des  =  rowinfo_[nrows() - 1].offset_
582                        + rowinfo_[nrows() - 1].descent_
583                  //+ hlinesep() * rowinfo_[nrows()].lines_
584                        + 1;
585 }
586
587
588 void MathGridInset::drawT(TextPainter & pain, int x, int y) const
589 {
590         for (idx_type idx = 0; idx < nargs(); ++idx)
591                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
592 }
593
594
595 string MathGridInset::eolString(row_type row, bool fragile) const
596 {
597         string eol;
598
599         if (!rowinfo_[row].crskip_.zero())
600                 eol += '[' + rowinfo_[row].crskip_.asLatexString() + ']';
601
602         // make sure an upcoming '[' does not break anything
603         if (row + 1 < nrows()) {
604                 MathArray const & c = cell(index(row + 1, 0));
605                 if (c.size() && c.front()->getChar() == '[')
606                         //eol += "[0pt]";
607                         eol += "{}";
608         }
609
610         // only add \\ if necessary
611         if (eol.empty() && row + 1 == nrows())
612                 return string();
613
614         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
615 }
616
617
618 string MathGridInset::eocString(col_type col, col_type lastcol) const
619 {
620         if (col + 1 == lastcol)
621                 return string();
622         return " & ";
623 }
624
625
626 void MathGridInset::addRow(row_type row)
627 {
628         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
629         cells_.insert
630                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathArray());
631         cellinfo_.insert
632                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
633 }
634
635
636 void MathGridInset::appendRow()
637 {
638         rowinfo_.push_back(RowInfo());
639         //cells_.insert(cells_.end(), ncols(), MathArray());
640         for (col_type col = 0; col < ncols(); ++col) {
641                 cells_.push_back(cells_type::value_type());
642                 cellinfo_.push_back(CellInfo());
643         }
644 }
645
646
647 void MathGridInset::delRow(row_type row)
648 {
649         if (nrows() == 1)
650                 return;
651
652         cells_type::iterator it = cells_.begin() + row * ncols();
653         cells_.erase(it, it + ncols());
654
655         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
656         cellinfo_.erase(jt, jt + ncols());
657
658         rowinfo_.erase(rowinfo_.begin() + row);
659 }
660
661
662 void MathGridInset::copyRow(row_type row)
663 {
664         addRow(row);
665         for (col_type col = 0; col < ncols(); ++col)
666                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
667 }
668
669
670 void MathGridInset::swapRow(row_type row)
671 {
672         if (nrows() == 1)
673                 return;
674         if (row + 1 == nrows())
675                 --row;
676         for (col_type col = 0; col < ncols(); ++col)
677                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
678 }
679
680
681 void MathGridInset::addCol(col_type newcol)
682 {
683         const col_type nc = ncols();
684         const row_type nr = nrows();
685         cells_type new_cells((nc + 1) * nr);
686         vector<CellInfo> new_cellinfo((nc + 1) * nr);
687
688         for (row_type row = 0; row < nr; ++row)
689                 for (col_type col = 0; col < nc; ++col) {
690                         new_cells[row * (nc + 1) + col + (col > newcol)]
691                                 = cells_[row * nc + col];
692                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
693                                 = cellinfo_[row * nc + col];
694                 }
695         swap(cells_, new_cells);
696         swap(cellinfo_, new_cellinfo);
697
698         ColInfo inf;
699         inf.skip_  = defaultColSpace(newcol);
700         inf.align_ = defaultColAlign(newcol);
701         colinfo_.insert(colinfo_.begin() + newcol, inf);
702 }
703
704
705 void MathGridInset::delCol(col_type col)
706 {
707         if (ncols() == 1)
708                 return;
709
710         cells_type tmpcells;
711         vector<CellInfo> tmpcellinfo;
712         for (col_type i = 0; i < nargs(); ++i)
713                 if (i % ncols() != col) {
714                         tmpcells.push_back(cells_[i]);
715                         tmpcellinfo.push_back(cellinfo_[i]);
716                 }
717         swap(cells_, tmpcells);
718         swap(cellinfo_, tmpcellinfo);
719
720         colinfo_.erase(colinfo_.begin() + col);
721 }
722
723
724 void MathGridInset::copyCol(col_type col)
725 {
726         addCol(col);
727         for (row_type row = 0; row < nrows(); ++row)
728                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
729 }
730
731
732 void MathGridInset::swapCol(col_type col)
733 {
734         if (ncols() == 1)
735                 return;
736         if (col + 1 == ncols())
737                 --col;
738         for (row_type row = 0; row < nrows(); ++row)
739                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
740 }
741
742
743 int MathGridInset::cellXOffset(idx_type idx) const
744 {
745         col_type c = col(idx);
746         int x = colinfo_[c].offset_;
747         char align = colinfo_[c].align_;
748         if (align == 'r' || align == 'R')
749                 x += colinfo_[c].width_ - cell(idx).width();
750         if (align == 'c' || align == 'C')
751                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
752         return x;
753 }
754
755
756 int MathGridInset::cellYOffset(idx_type idx) const
757 {
758         return rowinfo_[row(idx)].offset_;
759 }
760
761
762 bool MathGridInset::idxUpDown(LCursor & cur, bool up) const
763 {
764         if (up) {
765                 if (cur.idx() < ncols())
766                         return false;
767                 cur.idx() -= ncols();
768         } else {
769                 if (cur.idx() >= ncols() * (nrows() - 1))
770                         return false;
771                 cur.idx() += ncols();
772         }
773         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo());
774         return true;
775 }
776
777
778 bool MathGridInset::idxLeft(LCursor & cur) const
779 {
780         // leave matrix if on the left hand edge
781         if (cur.col() == 0)
782                 return false;
783         --cur.idx();
784         cur.pos() = cur.lastpos();
785         return true;
786 }
787
788
789 bool MathGridInset::idxRight(LCursor & cur) const
790 {
791         // leave matrix if on the right hand edge
792         if (cur.col() + 1 == ncols())
793                 return false;
794         ++cur.idx();
795         cur.pos() = 0;
796         return true;
797 }
798
799
800 bool MathGridInset::idxFirst(LCursor & cur) const
801 {
802         switch (v_align_) {
803                 case 't':
804                         cur.idx() = 0;
805                         break;
806                 case 'b':
807                         cur.idx() = (nrows() - 1) * ncols();
808                         break;
809                 default:
810                         cur.idx() = ((nrows() - 1) / 2) * ncols();
811         }
812         cur.pos() = 0;
813         return true;
814 }
815
816
817 bool MathGridInset::idxLast(LCursor & cur) const
818 {
819         switch (v_align_) {
820                 case 't':
821                         cur.idx() = ncols() - 1;
822                         break;
823                 case 'b':
824                         cur.idx() = nargs() - 1;
825                         break;
826                 default:
827                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
828         }
829         cur.pos() = cur.lastpos();
830         return true;
831 }
832
833
834 bool MathGridInset::idxDelete(idx_type & idx)
835 {
836         // nothing to do if we have just one row
837         if (nrows() == 1)
838                 return false;
839
840         // nothing to do if we are in the middle of the last row of the inset
841         if (idx + ncols() > nargs())
842                 return false;
843
844         // try to delete entire sequence of ncols() empty cells if possible
845         for (idx_type i = idx; i < idx + ncols(); ++i)
846                 if (cell(i).size())
847                         return false;
848
849         // move cells if necessary
850         for (idx_type i = index(row(idx), 0); i < idx; ++i)
851                 swap(cell(i), cell(i + ncols()));
852
853         delRow(row(idx));
854
855         if (idx >= nargs())
856                 idx = nargs() - 1;
857
858         // undo effect of Ctrl-Tab (i.e. pull next cell)
859         //if (idx + 1 != nargs())
860         //      cell(idx).swap(cell(idx + 1));
861
862         // we handled the event..
863         return true;
864 }
865
866
867 // reimplement old behaviour when pressing Delete in the last position
868 // of a cell
869 void MathGridInset::idxGlue(idx_type idx)
870 {
871         col_type c = col(idx);
872         if (c + 1 == ncols()) {
873                 if (row(idx) + 1 != nrows()) {
874                         for (col_type cc = 0; cc < ncols(); ++cc)
875                                 cell(idx).append(cell(idx + cc + 1));
876                         delRow(row(idx) + 1);
877                 }
878         } else {
879                 cell(idx).append(cell(idx + 1));
880                 for (col_type cc = c + 2; cc < ncols(); ++cc)
881                         cell(idx - c + cc - 1) = cell(idx - c + cc);
882                 cell(idx - c + ncols() - 1).clear();
883         }
884 }
885
886
887 MathGridInset::RowInfo const & MathGridInset::rowinfo(row_type row) const
888 {
889         return rowinfo_[row];
890 }
891
892
893 MathGridInset::RowInfo & MathGridInset::rowinfo(row_type row)
894 {
895         return rowinfo_[row];
896 }
897
898
899 bool MathGridInset::idxBetween(idx_type idx, idx_type from, idx_type to) const
900 {
901         row_type const ri = row(idx);
902         row_type const r1 = min(row(from), row(to));
903         row_type const r2 = max(row(from), row(to));
904         col_type const ci = col(idx);
905         col_type const c1 = min(col(from), col(to));
906         col_type const c2 = max(col(from), col(to));
907         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
908 }
909
910
911
912 void MathGridInset::normalize(NormalStream & os) const
913 {
914         os << "[grid ";
915         for (row_type row = 0; row < nrows(); ++row) {
916                 os << "[row ";
917                 for (col_type col = 0; col < ncols(); ++col)
918                         os << "[cell " << cell(index(row, col)) << ']';
919                 os << ']';
920         }
921         os << ']';
922 }
923
924
925 void MathGridInset::mathmlize(MathMLStream & os) const
926 {
927         os << MTag("mtable");
928         for (row_type row = 0; row < nrows(); ++row) {
929                 os << MTag("mtr");
930                 for (col_type col = 0; col < ncols(); ++col)
931                         os << cell(index(row, col));
932                 os << ETag("mtr");
933         }
934         os << ETag("mtable");
935 }
936
937
938 void MathGridInset::write(WriteStream & os) const
939 {
940         for (row_type row = 0; row < nrows(); ++row) {
941                 os << verboseHLine(rowinfo_[row].lines_);
942                 // don't write & and empty cells at end of line
943                 col_type lastcol = 0;
944                 bool emptyline = true;
945                 for (col_type col = 0; col < ncols(); ++col)
946                         if (!cell(index(row, col)).empty()) {
947                                 lastcol = col + 1;
948                                 emptyline = false;
949                         }
950                 for (col_type col = 0; col < lastcol; ++col)
951                         os << cell(index(row, col)) << eocString(col, lastcol);
952                 os << eolString(row, os.fragile());
953                 // append newline only if line wasn't completely empty
954                 // and this was not the last line in the grid
955                 if (!emptyline && row + 1 < nrows())
956                         os << "\n";
957         }
958         string const s = verboseHLine(rowinfo_[nrows()].lines_);
959         if (!s.empty() && s != " ") {
960                 if (os.fragile())
961                         os << "\\protect";
962                 os << "\\\\" << s;
963         }
964 }
965
966
967 int MathGridInset::colsep() const
968 {
969         return 6;
970 }
971
972
973 int MathGridInset::rowsep() const
974 {
975         return 6;
976 }
977
978
979 int MathGridInset::hlinesep() const
980 {
981         return 3;
982 }
983
984
985 int MathGridInset::vlinesep() const
986 {
987         return 3;
988 }
989
990
991 int MathGridInset::border() const
992 {
993         return 1;
994 }
995
996
997 void MathGridInset::splitCell(LCursor & cur)
998 {
999         if (cur.idx() == cur.lastidx())
1000                 return;
1001         MathArray ar = cur.cell();
1002         ar.erase(0, cur.pos());
1003         cur.cell().erase(cur.pos(), cur.lastpos());
1004         ++cur.idx();
1005         cur.pos() = 0;
1006         cur.cell().insert(0, ar);
1007 }
1008
1009
1010 void MathGridInset::priv_dispatch(LCursor & cur, FuncRequest & cmd)
1011 {
1012         //lyxerr << "*** MathGridInset: request: " << cmd << endl;
1013         switch (cmd.action) {
1014
1015         case LFUN_MOUSE_RELEASE:
1016                 //if (cmd.button() == mouse_button::button3) {
1017                 //      GridInsetMailer(*this).showDialog();
1018                 //      return DispatchResult(true, true);
1019                 //}
1020                 MathNestInset::priv_dispatch(cur, cmd);
1021                 break;
1022
1023         case LFUN_INSET_DIALOG_UPDATE:
1024                 GridInsetMailer(*this).updateDialog(&cur.bv());
1025                 break;
1026
1027         // insert file functions
1028         case LFUN_DELETE_LINE_FORWARD:
1029                 //autocorrect_ = false;
1030                 //macroModeClose();
1031                 //if (selection_) {
1032                 //      selDel();
1033                 //      break;
1034                 //}
1035                 if (nrows() > 1)
1036                         delRow(cur.row());
1037                 if (cur.idx() > cur.lastidx())
1038                         cur.idx() = cur.lastidx();
1039                 if (cur.pos() > cur.lastpos())
1040                         cur.pos() = cur.lastpos();
1041                 break;
1042
1043         case LFUN_CELL_SPLIT:
1044                 ////recordUndo(cur, Undo::ATOMIC);
1045                 splitCell(cur);
1046                 break;
1047
1048         case LFUN_BREAKLINE: {
1049                 ////recordUndo(cur, Undo::INSERT);
1050                 row_type const r = cur.row();
1051                 addRow(r);
1052
1053                 // split line
1054                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1055                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1056
1057                 // split cell
1058                 splitCell(cur);
1059                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1060                 if (cur.idx() > 0)
1061                         --cur.idx();
1062                 cur.idx() = cur.lastpos();
1063
1064                 //mathcursor->normalize();
1065                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
1066                 break;
1067         }
1068
1069         case LFUN_TABULAR_FEATURE: {
1070                 //lyxerr << "handling tabular-feature " << cmd.argument << endl;
1071                 istringstream is(cmd.argument);
1072                 string s;
1073                 is >> s;
1074                 if (s == "valign-top")
1075                         valign('t');
1076                 else if (s == "valign-middle")
1077                         valign('c');
1078                 else if (s == "valign-bottom")
1079                         valign('b');
1080                 else if (s == "align-left")
1081                         halign('l', col(cur.idx()));
1082                 else if (s == "align-right")
1083                         halign('r', col(cur.idx()));
1084                 else if (s == "align-center")
1085                         halign('c', col(cur.idx()));
1086                 else if (s == "append-row")
1087                         for (int i = 0, n = extractInt(is); i < n; ++i)
1088                                 addRow(cur.row());
1089                 else if (s == "delete-row")
1090                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1091                                 delRow(cur.row());
1092                                 if (cur.idx() > nargs())
1093                                         cur.idx() -= ncols();
1094                         }
1095                 else if (s == "copy-row")
1096                         for (int i = 0, n = extractInt(is); i < n; ++i)
1097                                 copyRow(cur.row());
1098                 else if (s == "swap-row")
1099                         swapRow(cur.row());
1100                 else if (s == "append-column")
1101                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1102                                 row_type r = cur.row();
1103                                 col_type c = col(cur.idx());
1104                                 addCol(c);
1105                                 cur.idx() = index(r, c);
1106                         }
1107                 else if (s == "delete-column")
1108                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1109                                 row_type r = cur.row();
1110                                 col_type c = col(cur.idx());
1111                                 delCol(col(cur.idx()));
1112                                 cur.idx() = index(r, c);
1113                                 if (cur.idx() > nargs())
1114                                         cur.idx() -= ncols();
1115                         }
1116                 else if (s == "copy-column")
1117                         copyCol(col(cur.idx()));
1118                 else if (s == "swap-column")
1119                         swapCol(col(cur.idx()));
1120                 else {
1121                         cur.undispatched();
1122                         break;
1123                 }
1124                 lyxerr << "returning FINISHED_LEFT" << endl;
1125                 break;
1126         }
1127
1128         case LFUN_PASTE: {
1129                 lyxerr << "MathGridInset: PASTE: " << cmd << std::endl;
1130                 istringstream is(cmd.argument);
1131                 int n = 0;
1132                 is >> n;
1133                 MathGridInset grid(1, 1);
1134                 mathed_parse_normal(grid, lyx::cap::getSelection(cur.buffer(), n));
1135                 if (grid.nargs() == 1) {
1136                         // single cell/part of cell
1137                         cur.cell().insert(cur.pos(), grid.cell(0));
1138                         cur.pos() += grid.cell(0).size();
1139                 } else {
1140                         // multiple cells
1141                         col_type const numcols =
1142                                 min(grid.ncols(), ncols() - col(cur.idx()));
1143                         row_type const numrows =
1144                                 min(grid.nrows(), nrows() - cur.row());
1145                         for (row_type r = 0; r < numrows; ++r) {
1146                                 for (col_type c = 0; c < numcols; ++c) {
1147                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1148                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1149                                 }
1150                                 // append the left over horizontal cells to the last column
1151                                 idx_type i = index(r + cur.row(), ncols() - 1);
1152                                 for (MathInset::col_type c = numcols; c < grid.ncols(); ++c)
1153                                         cell(i).append(grid.cell(grid.index(r, c)));
1154                         }
1155                         // append the left over vertical cells to the last _cell_
1156                         idx_type i = nargs() - 1;
1157                         for (row_type r = numrows; r < grid.nrows(); ++r)
1158                                 for (col_type c = 0; c < grid.ncols(); ++c)
1159                                         cell(i).append(grid.cell(grid.index(r, c)));
1160                 }
1161                 break;
1162         }
1163
1164         case LFUN_HOMESEL:
1165         case LFUN_HOME:
1166         case LFUN_WORDLEFTSEL:
1167         case LFUN_WORDLEFT:
1168                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
1169                 cur.macroModeClose();
1170                 if (cur.pos() != 0) {
1171                         cur.pos() = 0;
1172                 } else if (cur.idx() % cur.ncols() != 0) {
1173                         cur.idx() -= cur.idx() % cur.ncols();
1174                         cur.pos() = 0;
1175                 } else if (cur.idx() != 0) {
1176                         cur.idx() = 0;
1177                         cur.pos() = 0;
1178                 } else {
1179                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1180                 }
1181                 break;
1182
1183         case LFUN_WORDRIGHTSEL:
1184         case LFUN_WORDRIGHT:
1185         case LFUN_ENDSEL:
1186         case LFUN_END:
1187                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
1188                 cur.macroModeClose();
1189                 cur.clearTargetX();
1190                 if (cur.pos() != cur.lastpos()) {
1191                         cur.pos() = cur.lastpos();
1192                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1193                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1194                         cur.pos() = cur.lastpos();
1195                 } else if (cur.idx() != cur.lastidx()) {
1196                         cur.idx() = cur.lastidx();
1197                         cur.pos() = cur.lastpos();
1198                 } else {
1199                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1200                 }
1201                 break;
1202
1203         default:
1204                 MathNestInset::priv_dispatch(cur, cmd);
1205         }
1206 }
1207
1208
1209 bool MathGridInset::getStatus(LCursor & cur, FuncRequest const & cmd,
1210                 FuncStatus & flag) const
1211 {
1212         bool ret = true;
1213         switch (cmd.action) {
1214         case LFUN_TABULAR_FEATURE:
1215 #if 0
1216                 // should be more precise
1217                 if (v_align_ == '\0') {
1218                         flag.enable(true);
1219                         break;
1220                 }
1221                 if (cmd.argument.empty()) {
1222                         flag.enable(false);
1223                         break;
1224                 }
1225                 if (!contains("tcb", cmd.argument[0])) {
1226                         flag.enable(false);
1227                         break;
1228                 }
1229                 flag.setOnOff(cmd.argument[0] == v_align_);
1230 #endif
1231                 flag.enabled(true);
1232                 break;
1233         default:
1234                 ret = MathNestInset::getStatus(cur, cmd, flag);
1235                 break;
1236         }
1237         return ret;
1238 }