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