]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathGrid.cpp
* Inset:
[features.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) 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 }
506
507
508 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
509 {
510         metrics(mi);
511         dim = dim_;
512 }
513
514
515 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
516 {
517         drawWithMargin(pi, x, y, 0, 0);
518 }
519
520 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
521         int lmargin, int rmargin) const
522 {
523         for (idx_type idx = 0; idx < nargs(); ++idx)
524                 cell(idx).draw(pi, x + lmargin + cellXOffset(idx),
525                         y + cellYOffset(idx));
526
527         for (row_type row = 0; row <= nrows(); ++row)
528                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
529                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
530                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
531                         pi.pain.line(x + lmargin + 1, yy,
532                                      x + dim_.width() - rmargin - 1, yy,
533                                      Color::foreground);
534                 }
535
536         for (col_type col = 0; col <= ncols(); ++col)
537                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
538                         int xx = x + lmargin + colinfo_[col].offset_
539                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
540                         pi.pain.line(xx, y - dim_.ascent() + 1,
541                                      xx, y + dim_.descent() - 1,
542                                      Color::foreground);
543                 }
544         drawMarkers2(pi, x, y);
545 }
546
547
548 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
549 {
550         // let the cells adjust themselves
551         //InsetMathNest::metrics(mi);
552         for (idx_type i = 0; i < nargs(); ++i)
553                 cell(i).metricsT(mi, dim);
554
555         // compute absolute sizes of vertical structure
556         for (row_type row = 0; row < nrows(); ++row) {
557                 int asc  = 0;
558                 int desc = 0;
559                 for (col_type col = 0; col < ncols(); ++col) {
560                         MathData const & c = cell(index(row, col));
561                         asc  = max(asc,  c.ascent());
562                         desc = max(desc, c.descent());
563                 }
564                 rowinfo_[row].ascent_  = asc;
565                 rowinfo_[row].descent_ = desc;
566         }
567         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
568         rowinfo_[nrows()].ascent_  = 0;
569         rowinfo_[nrows()].descent_ = 0;
570
571         // compute vertical offsets
572         rowinfo_[0].offset_ = 0;
573         for (row_type row = 1; row <= nrows(); ++row) {
574                 rowinfo_[row].offset_  =
575                         rowinfo_[row - 1].offset_  +
576                         rowinfo_[row - 1].descent_ +
577                         //rowinfo_[row - 1].skipPixels() +
578                         1 + //rowsep() +
579                         //rowinfo_[row].lines_ * hlinesep() +
580                         rowinfo_[row].ascent_;
581         }
582
583         // adjust vertical offset
584         int h = 0;
585         switch (v_align_) {
586                 case 't':
587                         h = 0;
588                         break;
589                 case 'b':
590                         h = rowinfo_[nrows() - 1].offset_;
591                         break;
592                 default:
593                         h = rowinfo_[nrows() - 1].offset_ / 2;
594         }
595         for (row_type row = 0; row <= nrows(); ++row)
596                 rowinfo_[row].offset_ -= h;
597
598
599         // compute absolute sizes of horizontal structure
600         for (col_type col = 0; col < ncols(); ++col) {
601                 int wid = 0;
602                 for (row_type row = 0; row < nrows(); ++row)
603                         wid = max(wid, cell(index(row, col)).width());
604                 colinfo_[col].width_ = wid;
605         }
606         colinfo_[ncols()].width_  = 0;
607
608         // compute horizontal offsets
609         colinfo_[0].offset_ = border();
610         for (col_type col = 1; col <= ncols(); ++col) {
611                 colinfo_[col].offset_ =
612                         colinfo_[col - 1].offset_ +
613                         colinfo_[col - 1].width_ +
614                         colinfo_[col - 1].skip_ +
615                         1 ; //colsep() +
616                         //colinfo_[col].lines_ * vlinesep();
617         }
618
619
620         dim.wid  =  colinfo_[ncols() - 1].offset_
621                        + colinfo_[ncols() - 1].width_
622                  //+ vlinesep() * colinfo_[ncols()].lines_
623                        + 2;
624
625         dim.asc  = -rowinfo_[0].offset_
626                        + rowinfo_[0].ascent_
627                  //+ hlinesep() * rowinfo_[0].lines_
628                        + 1;
629
630         dim.des  =  rowinfo_[nrows() - 1].offset_
631                        + rowinfo_[nrows() - 1].descent_
632                  //+ hlinesep() * rowinfo_[nrows()].lines_
633                        + 1;
634 }
635
636
637 void InsetMathGrid::drawT(TextPainter & pain, int x, int y) const
638 {
639         for (idx_type idx = 0; idx < nargs(); ++idx)
640                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
641 }
642
643
644 docstring InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) const
645 {
646         docstring eol;
647
648         if (!rowinfo_[row].crskip_.zero())
649                 eol += '[' + from_utf8(rowinfo_[row].crskip_.asLatexString()) + ']';
650         else if(!rowinfo_[row].allow_pagebreak_)
651                 eol += '*';
652
653         // make sure an upcoming '[' does not break anything
654         if (row + 1 < nrows()) {
655                 MathData const & c = cell(index(row + 1, 0));
656                 if (c.size() && c.front()->getChar() == '[')
657                         //eol += "[0pt]";
658                         eol += "{}";
659         }
660
661         // only add \\ if necessary
662         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !emptyline))
663                 return docstring();
664
665         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
666 }
667
668
669 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
670 {
671         if (col + 1 == lastcol)
672                 return docstring();
673         return from_ascii(" & ");
674 }
675
676
677 void InsetMathGrid::addRow(row_type row)
678 {
679         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
680         cells_.insert
681                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathData());
682         cellinfo_.insert
683                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
684 }
685
686
687 void InsetMathGrid::appendRow()
688 {
689         rowinfo_.push_back(RowInfo());
690         //cells_.insert(cells_.end(), ncols(), MathData());
691         for (col_type col = 0; col < ncols(); ++col) {
692                 cells_.push_back(cells_type::value_type());
693                 cellinfo_.push_back(CellInfo());
694         }
695 }
696
697
698 void InsetMathGrid::delRow(row_type row)
699 {
700         if (nrows() == 1)
701                 return;
702
703         cells_type::iterator it = cells_.begin() + row * ncols();
704         cells_.erase(it, it + ncols());
705
706         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
707         cellinfo_.erase(jt, jt + ncols());
708
709         rowinfo_.erase(rowinfo_.begin() + row);
710 }
711
712
713 void InsetMathGrid::copyRow(row_type row)
714 {
715         addRow(row);
716         for (col_type col = 0; col < ncols(); ++col)
717                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
718 }
719
720
721 void InsetMathGrid::swapRow(row_type row)
722 {
723         if (nrows() == 1)
724                 return;
725         if (row + 1 == nrows())
726                 --row;
727         for (col_type col = 0; col < ncols(); ++col)
728                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
729 }
730
731
732 void InsetMathGrid::addCol(col_type newcol)
733 {
734         const col_type nc = ncols();
735         const row_type nr = nrows();
736         cells_type new_cells((nc + 1) * nr);
737         vector<CellInfo> new_cellinfo((nc + 1) * nr);
738
739         for (row_type row = 0; row < nr; ++row)
740                 for (col_type col = 0; col < nc; ++col) {
741                         new_cells[row * (nc + 1) + col + (col > newcol)]
742                                 = cells_[row * nc + col];
743                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
744                                 = cellinfo_[row * nc + col];
745                 }
746         swap(cells_, new_cells);
747         swap(cellinfo_, new_cellinfo);
748
749         ColInfo inf;
750         inf.skip_  = defaultColSpace(newcol);
751         inf.align_ = defaultColAlign(newcol);
752         colinfo_.insert(colinfo_.begin() + newcol, inf);
753 }
754
755
756 void InsetMathGrid::delCol(col_type col)
757 {
758         if (ncols() == 1)
759                 return;
760
761         cells_type tmpcells;
762         vector<CellInfo> tmpcellinfo;
763         for (col_type i = 0; i < nargs(); ++i)
764                 if (i % ncols() != col) {
765                         tmpcells.push_back(cells_[i]);
766                         tmpcellinfo.push_back(cellinfo_[i]);
767                 }
768         swap(cells_, tmpcells);
769         swap(cellinfo_, tmpcellinfo);
770
771         colinfo_.erase(colinfo_.begin() + col);
772 }
773
774
775 void InsetMathGrid::copyCol(col_type col)
776 {
777         addCol(col);
778         for (row_type row = 0; row < nrows(); ++row)
779                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
780 }
781
782
783 void InsetMathGrid::swapCol(col_type col)
784 {
785         if (ncols() == 1)
786                 return;
787         if (col + 1 == ncols())
788                 --col;
789         for (row_type row = 0; row < nrows(); ++row)
790                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
791 }
792
793
794 int InsetMathGrid::cellXOffset(idx_type idx) const
795 {
796         col_type c = col(idx);
797         int x = colinfo_[c].offset_;
798         char align = colinfo_[c].align_;
799         if (align == 'r' || align == 'R')
800                 x += colinfo_[c].width_ - cell(idx).width();
801         if (align == 'c' || align == 'C')
802                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
803         return x;
804 }
805
806
807 int InsetMathGrid::cellYOffset(idx_type idx) const
808 {
809         return rowinfo_[row(idx)].offset_;
810 }
811
812
813 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
814 {
815         if (up) {
816                 if (cur.row() == 0)
817                         return false;
818                 cur.idx() -= ncols();
819         } else {
820                 if (cur.row() + 1 >= nrows())
821                         return false;
822                 cur.idx() += ncols();
823         }
824         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo(cur.bv()));
825         return true;
826 }
827
828
829 bool InsetMathGrid::idxLeft(Cursor & cur) const
830 {
831         // leave matrix if on the left hand edge
832         if (cur.col() == 0)
833                 return false;
834         --cur.idx();
835         cur.pos() = cur.lastpos();
836         return true;
837 }
838
839
840 bool InsetMathGrid::idxRight(Cursor & cur) const
841 {
842         // leave matrix if on the right hand edge
843         if (cur.col() + 1 == ncols())
844                 return false;
845         ++cur.idx();
846         cur.pos() = 0;
847         return true;
848 }
849
850
851 bool InsetMathGrid::idxFirst(Cursor & cur) const
852 {
853         switch (v_align_) {
854                 case 't':
855                         cur.idx() = 0;
856                         break;
857                 case 'b':
858                         cur.idx() = (nrows() - 1) * ncols();
859                         break;
860                 default:
861                         cur.idx() = ((nrows() - 1) / 2) * ncols();
862         }
863         cur.pos() = 0;
864         return true;
865 }
866
867
868 bool InsetMathGrid::idxLast(Cursor & cur) const
869 {
870         switch (v_align_) {
871                 case 't':
872                         cur.idx() = ncols() - 1;
873                         break;
874                 case 'b':
875                         cur.idx() = nargs() - 1;
876                         break;
877                 default:
878                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
879         }
880         cur.pos() = cur.lastpos();
881         return true;
882 }
883
884
885 bool InsetMathGrid::idxDelete(idx_type & idx)
886 {
887         // nothing to do if we have just one row
888         if (nrows() == 1)
889                 return false;
890
891         // nothing to do if we are in the middle of the last row of the inset
892         if (idx + ncols() > nargs())
893                 return false;
894
895         // try to delete entire sequence of ncols() empty cells if possible
896         for (idx_type i = idx; i < idx + ncols(); ++i)
897                 if (cell(i).size())
898                         return false;
899
900         // move cells if necessary
901         for (idx_type i = index(row(idx), 0); i < idx; ++i)
902                 swap(cell(i), cell(i + ncols()));
903
904         delRow(row(idx));
905
906         if (idx >= nargs())
907                 idx = nargs() - 1;
908
909         // undo effect of Ctrl-Tab (i.e. pull next cell)
910         //if (idx + 1 != nargs())
911         //      cell(idx).swap(cell(idx + 1));
912
913         // we handled the event..
914         return true;
915 }
916
917
918 // reimplement old behaviour when pressing Delete in the last position
919 // of a cell
920 void InsetMathGrid::idxGlue(idx_type idx)
921 {
922         col_type c = col(idx);
923         if (c + 1 == ncols()) {
924                 if (row(idx) + 1 != nrows()) {
925                         for (col_type cc = 0; cc < ncols(); ++cc)
926                                 cell(idx).append(cell(idx + cc + 1));
927                         delRow(row(idx) + 1);
928                 }
929         } else {
930                 cell(idx).append(cell(idx + 1));
931                 for (col_type cc = c + 2; cc < ncols(); ++cc)
932                         cell(idx - c + cc - 1) = cell(idx - c + cc);
933                 cell(idx - c + ncols() - 1).clear();
934         }
935 }
936
937
938 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
939 {
940         return rowinfo_[row];
941 }
942
943
944 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
945 {
946         return rowinfo_[row];
947 }
948
949
950 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
951 {
952         row_type const ri = row(idx);
953         row_type const r1 = min(row(from), row(to));
954         row_type const r2 = max(row(from), row(to));
955         col_type const ci = col(idx);
956         col_type const c1 = min(col(from), col(to));
957         col_type const c2 = max(col(from), col(to));
958         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
959 }
960
961
962
963 void InsetMathGrid::normalize(NormalStream & os) const
964 {
965         os << "[grid ";
966         for (row_type row = 0; row < nrows(); ++row) {
967                 os << "[row ";
968                 for (col_type col = 0; col < ncols(); ++col)
969                         os << "[cell " << cell(index(row, col)) << ']';
970                 os << ']';
971         }
972         os << ']';
973 }
974
975
976 void InsetMathGrid::mathmlize(MathStream & os) const
977 {
978         os << MTag("mtable");
979         for (row_type row = 0; row < nrows(); ++row) {
980                 os << MTag("mtr");
981                 for (col_type col = 0; col < ncols(); ++col)
982                         os << cell(index(row, col));
983                 os << ETag("mtr");
984         }
985         os << ETag("mtable");
986 }
987
988
989 void InsetMathGrid::write(WriteStream & os) const
990 {
991         docstring eol;
992         for (row_type row = 0; row < nrows(); ++row) {
993                 os << verboseHLine(rowinfo_[row].lines_);
994                 // don't write & and empty cells at end of line
995                 col_type lastcol = 0;
996                 bool emptyline = true;
997                 for (col_type col = 0; col < ncols(); ++col)
998                         if (!cell(index(row, col)).empty()) {
999                                 lastcol = col + 1;
1000                                 emptyline = false;
1001                         }
1002                 for (col_type col = 0; col < lastcol; ++col)
1003                         os << cell(index(row, col)) << eocString(col, lastcol);
1004                 eol = eolString(row, emptyline, os.fragile());
1005                 os << eol;
1006                 // append newline only if line wasn't completely empty
1007                 // and this was not the last line in the grid
1008                 if (!emptyline && row + 1 < nrows())
1009                         os << "\n";
1010         }
1011         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
1012         if (!s.empty()) {
1013                 if (eol.empty()) {
1014                         if (os.fragile())
1015                                 os << "\\protect";
1016                         os << "\\\\";
1017                 }
1018                 os << s;
1019         }
1020 }
1021
1022
1023 int InsetMathGrid::colsep() const
1024 {
1025         return 6;
1026 }
1027
1028
1029 int InsetMathGrid::rowsep() const
1030 {
1031         return 6;
1032 }
1033
1034
1035 int InsetMathGrid::hlinesep() const
1036 {
1037         return 3;
1038 }
1039
1040
1041 int InsetMathGrid::vlinesep() const
1042 {
1043         return 3;
1044 }
1045
1046
1047 int InsetMathGrid::border() const
1048 {
1049         return 1;
1050 }
1051
1052
1053 void InsetMathGrid::splitCell(Cursor & cur)
1054 {
1055         if (cur.idx() == cur.lastidx())
1056                 return;
1057         MathData ar = cur.cell();
1058         ar.erase(0, cur.pos());
1059         cur.cell().erase(cur.pos(), cur.lastpos());
1060         ++cur.idx();
1061         cur.pos() = 0;
1062         cur.cell().insert(0, ar);
1063 }
1064
1065
1066 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1067 {
1068         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1069         switch (cmd.action) {
1070
1071         // insert file functions
1072         case LFUN_LINE_DELETE:
1073                 // FIXME: We use recordUndoInset when a change reflects more
1074                 // than one cell, because recordUndo does not work for
1075                 // multiple cells. Unfortunately this puts the cursor in front
1076                 // of the inset after undo. This is (especilally for large
1077                 // grids) annoying.
1078                 recordUndoInset(cur);
1079                 //autocorrect_ = false;
1080                 //macroModeClose();
1081                 //if (selection_) {
1082                 //      selDel();
1083                 //      break;
1084                 //}
1085                 if (nrows() > 1)
1086                         delRow(cur.row());
1087                 if (cur.idx() > cur.lastidx())
1088                         cur.idx() = cur.lastidx();
1089                 if (cur.pos() > cur.lastpos())
1090                         cur.pos() = cur.lastpos();
1091                 break;
1092
1093         case LFUN_CELL_SPLIT:
1094                 recordUndo(cur);
1095                 splitCell(cur);
1096                 break;
1097
1098         case LFUN_CELL_BACKWARD:
1099                 // See below.
1100                 cur.selection() = false;
1101                 if (!idxPrev(cur)) {
1102                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1103                         cur.undispatched();
1104                 }
1105                 break;
1106
1107         case LFUN_CELL_FORWARD:
1108                 // Can't handle selection by additional 'shift' as this is
1109                 // hard bound to LFUN_CELL_BACKWARD
1110                 cur.selection() = false;
1111                 if (!idxNext(cur)) {
1112                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1113                         cur.undispatched();
1114                 }
1115                 break;
1116
1117         case LFUN_BREAK_LINE: {
1118                 recordUndoInset(cur);
1119                 row_type const r = cur.row();
1120                 addRow(r);
1121
1122                 // split line
1123                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1124                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1125
1126                 // split cell
1127                 splitCell(cur);
1128                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1129                 if (cur.idx() > 0)
1130                         --cur.idx();
1131                 cur.pos() = cur.lastpos();
1132
1133                 //mathcursor->normalize();
1134                 //cmd = FuncRequest(LFUN_FINISHED_LEFT);
1135                 break;
1136         }
1137
1138         case LFUN_TABULAR_FEATURE: {
1139                 recordUndoInset(cur);
1140                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1141                 istringstream is(to_utf8(cmd.argument()));
1142                 string s;
1143                 is >> s;
1144                 if (s == "valign-top")
1145                         valign('t');
1146                 else if (s == "valign-middle")
1147                         valign('c');
1148                 else if (s == "valign-bottom")
1149                         valign('b');
1150                 else if (s == "align-left")
1151                         halign('l', cur.col());
1152                 else if (s == "align-right")
1153                         halign('r', cur.col());
1154                 else if (s == "align-center")
1155                         halign('c', cur.col());
1156                 else if (s == "append-row")
1157                         for (int i = 0, n = extractInt(is); i < n; ++i)
1158                                 addRow(cur.row());
1159                 else if (s == "delete-row") {
1160                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1161                                 delRow(cur.row());
1162                                 if (cur.idx() >= nargs())
1163                                         cur.idx() -= ncols();
1164                         }
1165                         cur.pos() = 0; // trick, see below
1166                 }
1167                 else if (s == "copy-row") {
1168                         // Here (as later) we save the cursor col/row
1169                         // in order to restore it after operation.
1170                         row_type const r = cur.row();
1171                         col_type const c = cur.col();
1172                         for (int i = 0, n = extractInt(is); i < n; ++i)
1173                                 copyRow(cur.row());
1174                         cur.idx() = index(r, c);
1175                 }
1176                 else if (s == "swap-row") {
1177                         swapRow(cur.row());
1178                         // Trick to suppress same-idx-means-different-cell
1179                         // assertion crash:
1180                         cur.pos() = 0;
1181                 }
1182                 else if (s == "add-hline-above")
1183                         rowinfo_[cur.row()].lines_++;
1184                 else if (s == "add-hline-below")
1185                         rowinfo_[cur.row()+1].lines_++;
1186                 else if (s == "delete-hline-above")
1187                         rowinfo_[cur.row()].lines_--;
1188                 else if (s == "delete-hline-below")
1189                         rowinfo_[cur.row()+1].lines_--;
1190                 else if (s == "append-column") {
1191                         row_type const r = cur.row();
1192                         col_type const c = cur.col();
1193                         for (int i = 0, n = extractInt(is); i < n; ++i)
1194                                 addCol(cur.col());
1195                         cur.idx() = index(r, c);
1196                 }
1197                 else if (s == "delete-column") {
1198                         row_type const r = cur.row();
1199                         col_type const c = cur.col();
1200                         for (int i = 0, n = extractInt(is); i < n; ++i)
1201                                 delCol(col(cur.idx()));
1202                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1203                         cur.pos() = 0; // trick, see above
1204                 }
1205                 else if (s == "copy-column") {
1206                         row_type const r = cur.row();
1207                         col_type const c = cur.col();
1208                         copyCol(cur.col());
1209                         cur.idx() = index(r, c);
1210                 }
1211                 else if (s == "swap-column") {
1212                         swapCol(cur.col());
1213                         cur.pos() = 0; // trick, see above
1214                 }
1215                 else if (s == "add-vline-left") {
1216                         colinfo_[cur.col()].lines_++;
1217                         if (!colinfo_[cur.col()].special_.empty())
1218                                 colinfo_[cur.col()].special_ += '|';
1219                 }
1220                 else if (s == "add-vline-right") {
1221                         colinfo_[cur.col()+1].lines_++;
1222                         if (!colinfo_[cur.col()+1].special_.empty())
1223                                 colinfo_[cur.col()+1].special_.insert(0, 1, '|');
1224                 }
1225                 else if (s == "delete-vline-left") {
1226                         colinfo_[cur.col()].lines_--;
1227                         docstring & special = colinfo_[cur.col()].special_;
1228                         if (!special.empty()) {
1229                                 docstring::size_type i = special.rfind('|');
1230                                 BOOST_ASSERT(i != docstring::npos);
1231                                 special.erase(i, 1);
1232                         }
1233                 }
1234                 else if (s == "delete-vline-right") {
1235                         colinfo_[cur.col()+1].lines_--;
1236                         docstring & special = colinfo_[cur.col()+1].special_;
1237                         if (!special.empty()) {
1238                                 docstring::size_type i = special.find('|');
1239                                 BOOST_ASSERT(i != docstring::npos);
1240                                 special.erase(i, 1);
1241                         }
1242                 }
1243                 else {
1244                         cur.undispatched();
1245                         break;
1246                 }
1247                 lyxerr << "returning FINISHED_LEFT" << endl;
1248                 break;
1249         }
1250
1251         case LFUN_PASTE: {
1252                 cur.message(_("Paste"));
1253                 cap::replaceSelection(cur);
1254                 docstring topaste;
1255                 if (cmd.argument().empty() && !theClipboard().isInternal())
1256                         topaste = theClipboard().getAsText();
1257                 else {
1258                         idocstringstream is(cmd.argument());
1259                         int n = 0;
1260                         is >> n;
1261                         topaste = cap::getSelection(cur.buffer(), n);
1262                 }
1263                 InsetMathGrid grid(1, 1);
1264                 if (!topaste.empty())
1265                         mathed_parse_normal(grid, topaste);
1266
1267                 if (grid.nargs() == 1) {
1268                         // single cell/part of cell
1269                         recordUndo(cur);
1270                         cur.cell().insert(cur.pos(), grid.cell(0));
1271                         cur.pos() += grid.cell(0).size();
1272                 } else {
1273                         // multiple cells
1274                         recordUndoInset(cur);
1275                         col_type const numcols =
1276                                 min(grid.ncols(), ncols() - col(cur.idx()));
1277                         row_type const numrows =
1278                                 min(grid.nrows(), nrows() - cur.row());
1279                         for (row_type r = 0; r < numrows; ++r) {
1280                                 for (col_type c = 0; c < numcols; ++c) {
1281                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1282                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1283                                 }
1284                                 // append the left over horizontal cells to the last column
1285                                 idx_type i = index(r + cur.row(), ncols() - 1);
1286                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1287                                         cell(i).append(grid.cell(grid.index(r, c)));
1288                         }
1289                         // append the left over vertical cells to the last _cell_
1290                         idx_type i = nargs() - 1;
1291                         for (row_type r = numrows; r < grid.nrows(); ++r)
1292                                 for (col_type c = 0; c < grid.ncols(); ++c)
1293                                         cell(i).append(grid.cell(grid.index(r, c)));
1294                 }
1295                 cur.clearSelection(); // bug 393
1296                 finishUndo();
1297                 break;
1298         }
1299
1300         case LFUN_LINE_BEGIN_SELECT:
1301         case LFUN_LINE_BEGIN:
1302         case LFUN_WORD_BACKWARD_SELECT:
1303         case LFUN_WORD_BACKWARD:
1304                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
1305                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
1306                 cur.macroModeClose();
1307                 if (cur.pos() != 0) {
1308                         cur.pos() = 0;
1309                 } else if (cur.idx() % cur.ncols() != 0) {
1310                         cur.idx() -= cur.idx() % cur.ncols();
1311                         cur.pos() = 0;
1312                 } else if (cur.idx() != 0) {
1313                         cur.idx() = 0;
1314                         cur.pos() = 0;
1315                 } else {
1316                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1317                         cur.undispatched();
1318                 }
1319                 break;
1320
1321         case LFUN_WORD_FORWARD_SELECT:
1322         case LFUN_WORD_FORWARD:
1323         case LFUN_LINE_END_SELECT:
1324         case LFUN_LINE_END:
1325                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
1326                                 cmd.action == LFUN_LINE_END_SELECT);
1327                 cur.macroModeClose();
1328                 cur.clearTargetX();
1329                 if (cur.pos() != cur.lastpos()) {
1330                         cur.pos() = cur.lastpos();
1331                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1332                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1333                         cur.pos() = cur.lastpos();
1334                 } else if (cur.idx() != cur.lastidx()) {
1335                         cur.idx() = cur.lastidx();
1336                         cur.pos() = cur.lastpos();
1337                 } else {
1338                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1339                         cur.undispatched();
1340                 }
1341                 break;
1342
1343         default:
1344                 InsetMathNest::doDispatch(cur, cmd);
1345         }
1346 }
1347
1348
1349 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1350                 FuncStatus & status) const
1351 {
1352         switch (cmd.action) {
1353         case LFUN_TABULAR_FEATURE: {
1354                 string const s = to_utf8(cmd.argument());
1355                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1356                         status.enabled(false);
1357                         status.message(from_utf8(N_("Only one row")));
1358                         return true;
1359                 }
1360                 if (ncols() <= 1 &&
1361                     (s == "delete-column" || s == "swap-column")) {
1362                         status.enabled(false);
1363                         status.message(from_utf8(N_("Only one column")));
1364                         return true;
1365                 }
1366                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1367                      s == "delete-hline-above") ||
1368                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1369                      s == "delete-hline-below")) {
1370                         status.enabled(false);
1371                         status.message(from_utf8(N_("No hline to delete")));
1372                         return true;
1373                 }
1374
1375                 if ((colinfo_[cur.col()].lines_ == 0 &&
1376                      s == "delete-vline-left") ||
1377                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1378                      s == "delete-vline-right")) {
1379                         status.enabled(false);
1380                         status.message(from_utf8(N_("No vline to delete")));
1381                         return true;
1382                 }
1383                 if (s == "valign-top" || s == "valign-middle" ||
1384                     s == "valign-bottom" || s == "align-left" ||
1385                     s == "align-right" || s == "align-center" ||
1386                     s == "append-row" || s == "delete-row" ||
1387                     s == "copy-row" || s == "swap-row" ||
1388                     s == "add-hline-above" || s == "add-hline-below" ||
1389                     s == "delete-hline-above" || s == "delete-hline-below" ||
1390                     s == "append-column" || s == "delete-column" ||
1391                     s == "copy-column" || s == "swap-column" ||
1392                     s == "add-vline-left" || s == "add-vline-right" ||
1393                     s == "delete-vline-left" || s == "delete-vline-right")
1394                         status.enabled(true);
1395                 else {
1396                         status.enabled(false);
1397                         status.message(bformat(
1398                                 from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1399                 }
1400
1401                 status.setOnOff((s == "align-left" && halign(cur.col()) == 'l')
1402                            || (s == "align-right"   && halign(cur.col()) == 'r')
1403                            || (s == "align-center"  && halign(cur.col()) == 'c')
1404                            || (s == "valign-top"    && valign() == 't')
1405                            || (s == "valign-bottom" && valign() == 'b')
1406                            || (s == "valign-middle" && valign() == 'm'));
1407
1408 #if 0
1409                 // FIXME: What did this code do?
1410                 // Please check whether it is still needed!
1411                 // should be more precise
1412                 if (v_align_ == '\0') {
1413                         status.enable(true);
1414                         break;
1415                 }
1416                 if (cmd.argument().empty()) {
1417                         status.enable(false);
1418                         break;
1419                 }
1420                 if (!support::contains("tcb", cmd.argument()[0])) {
1421                         status.enable(false);
1422                         break;
1423                 }
1424                 status.setOnOff(cmd.argument()[0] == v_align_);
1425                 status.enabled(true);
1426 #endif
1427                 return true;
1428         }
1429
1430         case LFUN_CELL_SPLIT:
1431                 status.enabled(true);
1432                 return true;
1433
1434         case LFUN_CELL_BACKWARD:
1435         case LFUN_CELL_FORWARD:
1436                 status.enabled(true);
1437                 return true;
1438
1439         default:
1440                 return InsetMathNest::getStatus(cur, cmd, status);
1441         }
1442 }
1443
1444
1445 } // namespace lyx