]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
* src/insets/InsetTabular.{cpp,h}:
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "InsetTabular.h"
21
22 #include "buffer_funcs.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Counters.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Language.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "OutputParams.h"
40 #include "paragraph_funcs.h"
41 #include "Paragraph.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/FileName.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption" },
155         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
156         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
157         { Tabular::SET_BOOKTABS, "set-booktabs" },
158         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
159         { Tabular::SET_TOP_SPACE, "set-top-space" },
160         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
161         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
162         { Tabular::SET_BORDER_LINES, "set-border-lines" },
163         { Tabular::LAST_ACTION, "" }
164 };
165
166
167 class FeatureEqual : public unary_function<TabularFeature, bool> {
168 public:
169         FeatureEqual(Tabular::Feature feature)
170                 : feature_(feature) {}
171         bool operator()(TabularFeature const & tf) const {
172                 return tf.action == feature_;
173         }
174 private:
175         Tabular::Feature feature_;
176 };
177
178
179 template <class T>
180 string const write_attribute(string const & name, T const & t)
181 {
182         string const s = tostr(t);
183         return s.empty() ? s : " " + name + "=\"" + s + "\"";
184 }
185
186 template <>
187 string const write_attribute(string const & name, string const & t)
188 {
189         return t.empty() ? t : " " + name + "=\"" + t + "\"";
190 }
191
192
193 template <>
194 string const write_attribute(string const & name, docstring const & t)
195 {
196         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
197 }
198
199
200 template <>
201 string const write_attribute(string const & name, bool const & b)
202 {
203         // we write only true attribute values so we remove a bit of the
204         // file format bloat for tabulars.
205         return b ? write_attribute(name, convert<string>(b)) : string();
206 }
207
208
209 template <>
210 string const write_attribute(string const & name, int const & i)
211 {
212         // we write only true attribute values so we remove a bit of the
213         // file format bloat for tabulars.
214         return i ? write_attribute(name, convert<string>(i)) : string();
215 }
216
217
218 template <>
219 string const write_attribute(string const & name, Tabular::idx_type const & i)
220 {
221         // we write only true attribute values so we remove a bit of the
222         // file format bloat for tabulars.
223         return i ? write_attribute(name, convert<string>(i)) : string();
224 }
225
226
227 template <>
228 string const write_attribute(string const & name, Length const & value)
229 {
230         // we write only the value if we really have one same reson as above.
231         return value.zero() ? string() : write_attribute(name, value.asString());
232 }
233
234
235 string const tostr(LyXAlignment const & num)
236 {
237         switch (num) {
238         case LYX_ALIGN_NONE:
239                 return "none";
240         case LYX_ALIGN_BLOCK:
241                 return "block";
242         case LYX_ALIGN_LEFT:
243                 return "left";
244         case LYX_ALIGN_CENTER:
245                 return "center";
246         case LYX_ALIGN_RIGHT:
247                 return "right";
248         case LYX_ALIGN_LAYOUT:
249                 return "layout";
250         case LYX_ALIGN_SPECIAL:
251                 return "special";
252         }
253         return string();
254 }
255
256
257 string const tostr(Tabular::VAlignment const & num)
258 {
259         switch (num) {
260         case Tabular::LYX_VALIGN_TOP:
261                 return "top";
262         case Tabular::LYX_VALIGN_MIDDLE:
263                 return "middle";
264         case Tabular::LYX_VALIGN_BOTTOM:
265                 return "bottom";
266         }
267         return string();
268 }
269
270
271 string const tostr(Tabular::BoxType const & num)
272 {
273         switch (num) {
274         case Tabular::BOX_NONE:
275                 return "none";
276         case Tabular::BOX_PARBOX:
277                 return "parbox";
278         case Tabular::BOX_MINIPAGE:
279                 return "minipage";
280         }
281         return string();
282 }
283
284
285 // I would have liked a fromstr template a lot better. (Lgb)
286 bool string2type(string const str, LyXAlignment & num)
287 {
288         if (str == "none")
289                 num = LYX_ALIGN_NONE;
290         else if (str == "block")
291                 num = LYX_ALIGN_BLOCK;
292         else if (str == "left")
293                 num = LYX_ALIGN_LEFT;
294         else if (str == "center")
295                 num = LYX_ALIGN_CENTER;
296         else if (str == "right")
297                 num = LYX_ALIGN_RIGHT;
298         else
299                 return false;
300         return true;
301 }
302
303
304 bool string2type(string const str, Tabular::VAlignment & num)
305 {
306         if (str == "top")
307                 num = Tabular::LYX_VALIGN_TOP;
308         else if (str == "middle" )
309                 num = Tabular::LYX_VALIGN_MIDDLE;
310         else if (str == "bottom")
311                 num = Tabular::LYX_VALIGN_BOTTOM;
312         else
313                 return false;
314         return true;
315 }
316
317
318 bool string2type(string const str, Tabular::BoxType & num)
319 {
320         if (str == "none")
321                 num = Tabular::BOX_NONE;
322         else if (str == "parbox")
323                 num = Tabular::BOX_PARBOX;
324         else if (str == "minipage")
325                 num = Tabular::BOX_MINIPAGE;
326         else
327                 return false;
328         return true;
329 }
330
331
332 bool string2type(string const str, bool & num)
333 {
334         if (str == "true")
335                 num = true;
336         else if (str == "false")
337                 num = false;
338         else
339                 return false;
340         return true;
341 }
342
343
344 bool getTokenValue(string const & str, char const * token, string & ret)
345 {
346         ret.erase();
347         size_t token_length = strlen(token);
348         size_t pos = str.find(token);
349
350         if (pos == string::npos || pos + token_length + 1 >= str.length()
351                 || str[pos + token_length] != '=')
352                 return false;
353         pos += token_length + 1;
354         char ch = str[pos];
355         if (ch != '"' && ch != '\'') { // only read till next space
356                 ret += ch;
357                 ch = ' ';
358         }
359         while (pos < str.length() - 1 && str[++pos] != ch)
360                 ret += str[pos];
361
362         return true;
363 }
364
365
366 bool getTokenValue(string const & str, char const * token, docstring & ret)
367 {
368         string tmp;
369         bool const success = getTokenValue(str, token, tmp);
370         ret = from_utf8(tmp);
371         return success;
372 }
373
374
375 bool getTokenValue(string const & str, char const * token, int & num)
376 {
377         string tmp;
378         num = 0;
379         if (!getTokenValue(str, token, tmp))
380                 return false;
381         num = convert<int>(tmp);
382         return true;
383 }
384
385
386 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
387 {
388         string tmp;
389         return getTokenValue(str, token, tmp) && string2type(tmp, num);
390 }
391
392
393 bool getTokenValue(string const & str, char const * token,
394                                    Tabular::VAlignment & num)
395 {
396         string tmp;
397         return getTokenValue(str, token, tmp) && string2type(tmp, num);
398 }
399
400
401 bool getTokenValue(string const & str, char const * token,
402                                    Tabular::BoxType & num)
403 {
404         string tmp;
405         return getTokenValue(str, token, tmp) && string2type(tmp, num);
406 }
407
408
409 bool getTokenValue(string const & str, char const * token, bool & flag)
410 {
411         // set the flag always to false as this should be the default for bools
412         // not in the file-format.
413         flag = false;
414         string tmp;
415         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
416 }
417
418
419 bool getTokenValue(string const & str, char const * token, Length & len)
420 {
421         // set the length to be zero() as default as this it should be if not
422         // in the file format.
423         len = Length();
424         string tmp;
425         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
426 }
427
428
429 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
430 {
431         len = Length();
432         flag = false;
433         string tmp;
434         if (!getTokenValue(str, token, tmp))
435                 return false;
436         if (tmp == "default") {
437                 flag = true;
438                 return  true;
439         }
440         return isValidLength(tmp, &len);
441 }
442
443
444 void l_getline(istream & is, string & str)
445 {
446         str.erase();
447         while (str.empty()) {
448                 getline(is, str);
449                 if (!str.empty() && str[str.length() - 1] == '\r')
450                         str.erase(str.length() - 1);
451         }
452 }
453
454 } // namespace
455
456
457 string const featureAsString(Tabular::Feature feature)
458 {
459         TabularFeature * end = tabularFeature +
460                 sizeof(tabularFeature) / sizeof(TabularFeature);
461         TabularFeature * it = find_if(tabularFeature, end,
462                                            FeatureEqual(feature));
463         return (it == end) ? string() : it->feature;
464 }
465
466
467
468 /////////////////////////////////////////////////////////////////////
469 //
470 // Tabular
471 //
472 /////////////////////////////////////////////////////////////////////
473
474
475 Tabular::CellData::CellData(Buffer & buf)
476         : cellno(0),
477           width(0),
478           multicolumn(Tabular::CELL_NORMAL),
479           alignment(LYX_ALIGN_CENTER),
480           valignment(LYX_VALIGN_TOP),
481           top_line(false),
482           bottom_line(false),
483           left_line(false),
484           right_line(false),
485           usebox(BOX_NONE),
486           rotate(false),
487           inset(new InsetTableCell(buf))
488 {
489         inset->setBuffer(const_cast<Buffer &>(buf));
490         inset->paragraphs().back().setLayout(buf.params().documentClass().plainLayout());
491 }
492
493
494 Tabular::CellData::CellData(CellData const & cs)
495         : cellno(cs.cellno),
496           width(cs.width),
497           multicolumn(cs.multicolumn),
498           alignment(cs.alignment),
499           valignment(cs.valignment),
500           top_line(cs.top_line),
501           bottom_line(cs.bottom_line),
502           left_line(cs.left_line),
503           right_line(cs.right_line),
504           usebox(cs.usebox),
505           rotate(cs.rotate),
506           align_special(cs.align_special),
507           p_width(cs.p_width),
508           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
509 {
510 }
511
512 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
513 {
514         swap(cs);
515         return *this;
516 }
517
518 void Tabular::CellData::swap(CellData & rhs)
519 {
520         std::swap(cellno, rhs.cellno);
521         std::swap(width, rhs.width);
522         std::swap(multicolumn, rhs.multicolumn);
523         std::swap(alignment, rhs.alignment);
524         std::swap(valignment, rhs.valignment);
525         std::swap(top_line, rhs.top_line);
526         std::swap(bottom_line, rhs.bottom_line);
527         std::swap(left_line, rhs.left_line);
528         std::swap(right_line, rhs.right_line);
529         std::swap(usebox, rhs.usebox);
530         std::swap(rotate, rhs.rotate);
531         std::swap(align_special, rhs.align_special);
532         p_width.swap(rhs.p_width);
533         inset.swap(rhs.inset);
534 }
535
536
537 Tabular::RowData::RowData()
538         : ascent(0),
539           descent(0),
540           top_space_default(false),
541           bottom_space_default(false),
542           interline_space_default(false),
543           endhead(false),
544           endfirsthead(false),
545           endfoot(false),
546           endlastfoot(false),
547           newpage(false),
548           caption(false)
549 {}
550
551
552 Tabular::ColumnData::ColumnData()
553         : alignment(LYX_ALIGN_CENTER),
554           valignment(LYX_VALIGN_TOP),
555           width(0)
556 {
557 }
558
559
560 Tabular::ltType::ltType()
561         : topDL(false),
562           bottomDL(false),
563           empty(false)
564 {}
565
566
567 Tabular::Tabular(Buffer & buffer, row_type rows_arg, col_type columns_arg)
568 {
569         init(buffer, rows_arg, columns_arg);
570 }
571
572
573 void Tabular::setBuffer(Buffer & buffer)
574 {
575         buffer_ = &buffer;
576         size_t row_count = row_info.size();
577         size_t column_count = column_info.size();
578         // set silly default lines
579         for (row_type i = 0; i < row_count; ++i)
580                 for (col_type j = 0; j < column_count; ++j)
581                         cell_info[i][j].inset->setBuffer(*buffer_);
582 }
583
584
585 // activates all lines and sets all widths to 0
586 void Tabular::init(Buffer & buf, row_type rows_arg,
587                       col_type columns_arg)
588 {
589         buffer_ = &buf;
590         row_info = row_vector(rows_arg);
591         column_info = column_vector(columns_arg);
592         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
593         row_info.reserve(10);
594         column_info.reserve(10);
595         cell_info.reserve(100);
596         updateIndexes();
597         is_long_tabular = false;
598         rotate = false;
599         use_booktabs = false;
600         size_t row_count = row_info.size();
601         size_t column_count = column_info.size();
602         // set silly default lines
603         for (row_type i = 0; i < row_count; ++i)
604                 for (col_type j = 0; j < column_count; ++j) {
605                         cell_info[i][j].inset->setBuffer(*buffer_);
606                         cell_info[i][j].top_line = true;
607                         cell_info[i][j].left_line = true;
608                         cell_info[i][j].bottom_line = i == 0 || i == row_count - 1;
609                         cell_info[i][j].right_line = j == column_count - 1;
610                 }
611 }
612
613
614 void Tabular::appendRow(idx_type const cell)
615 {
616         BufferParams const & bp = buffer().params();
617         row_type const row = cellRow(cell);
618
619         row_vector::iterator rit = row_info.begin() + row;
620         row_info.insert(rit, RowData());
621         // now set the values of the row before
622         row_info[row] = row_info[row + 1];
623
624         row_type const nrows = row_info.size();
625         col_type const ncols = column_info.size();
626
627         cell_vvector old(nrows - 1);
628         for (row_type i = 0; i < nrows - 1; ++i)
629                 swap(cell_info[i], old[i]);
630
631         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer())));
632
633         for (row_type i = 0; i <= row; ++i)
634                 swap(cell_info[i], old[i]);
635         for (row_type i = row + 2; i < nrows; ++i)
636                 swap(cell_info[i], old[i - 1]);
637
638         updateIndexes();
639         for (col_type c = 0; c < ncols; ++c) {
640                 // inherit line settings
641                 idx_type const i = cellIndex(row + 1, c);
642                 idx_type const j = cellIndex(row, c);
643                 setLeftLine(i, leftLine(j));
644                 setRightLine(i, rightLine(j));
645                 setTopLine(i, topLine(j));
646                 if (topLine(j) && bottomLine(j)) {
647                         setBottomLine(i, true);
648                         setBottomLine(j, false);
649                 }
650                 // mark track changes
651                 if (bp.trackChanges)
652                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
653         }
654 }
655
656
657 void Tabular::deleteRow(row_type const row)
658 {
659         // Not allowed to delete last row
660         if (row_info.size() == 1)
661                 return;
662
663         row_info.erase(row_info.begin() + row);
664         cell_info.erase(cell_info.begin() + row);
665         updateIndexes();
666 }
667
668
669 void Tabular::copyRow(row_type const row)
670 {
671         row_info.insert(row_info.begin() + row, row_info[row]);
672         cell_info.insert(cell_info.begin() + row, cell_info[row]);
673
674         if (buffer().params().trackChanges)
675                 for (col_type j = 0; j < column_info.size(); ++j)
676                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
677
678         updateIndexes();
679 }
680
681
682 void Tabular::appendColumn(idx_type const cell)
683 {
684         col_type const c = cellColumn(cell);
685         column_vector::iterator cit = column_info.begin() + c + 1;
686         column_info.insert(cit, ColumnData());
687         row_type const nrows = row_info.size();
688         // set the column values of the column before
689         column_info[c + 1] = column_info[c];
690
691         for (row_type r = 0; r < nrows; ++r) {
692                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
693                         CellData(buffer()));
694                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
695                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
696                 else
697                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
698         }
699         updateIndexes();
700         for (row_type r = 0; r < nrows; ++r) {
701                 // inherit line settings
702                 idx_type const i = cellIndex(r, c + 1);
703                 idx_type const j = cellIndex(r, c);
704                 setBottomLine(i, bottomLine(j));
705                 setTopLine(i, topLine(j));
706                 setLeftLine(i, leftLine(j));
707                 if (rightLine(j) && rightLine(j)) {
708                         setRightLine(i, true);
709                         setRightLine(j, false);
710                 }
711                 //
712                 cellInfo(i).inset->clear();
713                 if (buffer().params().trackChanges)
714                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
715         }
716 }
717
718
719 void Tabular::deleteColumn(col_type const column)
720 {
721         // Not allowed to delete last column
722         if (column_info.size() == 1)
723                 return;
724
725         column_info.erase(column_info.begin() + column);
726         size_t row_count = row_info.size();
727         for (row_type i = 0; i < row_count; ++i) {
728                 // Care about multicolumn cells
729                 if (column + 1 < column_info.size() &&
730                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
731                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
732                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
733                 }
734                 cell_info[i].erase(cell_info[i].begin() + column);
735         }
736         updateIndexes();
737 }
738
739
740 void Tabular::copyColumn(col_type const column)
741 {
742         BufferParams const & bp = buffer().params();
743         column_info.insert(column_info.begin() + column, column_info[column]);
744
745         size_t row_count = row_info.size();
746         for (row_type i = 0; i < row_count; ++i)
747                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
748
749         if (bp.trackChanges)
750                 for (row_type i = 0; i < row_count; ++i)
751                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
752         updateIndexes();
753 }
754
755
756 void Tabular::updateIndexes()
757 {
758         col_type ncols = column_info.size();
759         row_type nrows = row_info.size();
760         numberofcells = 0;
761         for (row_type row = 0; row < nrows; ++row)
762                 for (col_type column = 0; column < ncols; ++column) {
763                         if (!isPartOfMultiColumn(row, column))
764                                 ++numberofcells;
765                         cell_info[row][column].cellno = numberofcells - 1;
766                 }
767
768         rowofcell.resize(numberofcells);
769         columnofcell.resize(numberofcells);
770         idx_type i = 0;
771         for (row_type row = 0; row < nrows; ++row)
772                 for (col_type column = 0; column < ncols; ++column) {
773                         if (isPartOfMultiColumn(row, column))
774                                 continue;
775                         rowofcell[i] = row;
776                         columnofcell[i] = column;
777                         setFixedWidth(row, column);
778                         updateContentAlignment(row, column);
779                         ++i;
780                 }
781 }
782
783
784 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
785 {
786         row_type const row = cellRow(cell);
787         idx_type result = 0;
788         for (col_type i = 0; i < column_info.size(); ++i)
789                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
790                         ++result;
791         return result;
792 }
793
794
795 bool Tabular::topLine(idx_type const cell) const
796 {
797         return cellInfo(cell).top_line;
798 }
799
800
801 bool Tabular::bottomLine(idx_type const cell) const
802 {
803         return cellInfo(cell).bottom_line;
804 }
805
806
807 bool Tabular::leftLine(idx_type cell) const
808 {
809         if (use_booktabs)
810                 return false;
811         return cellInfo(cell).left_line;
812 }
813
814
815 bool Tabular::rightLine(idx_type cell) const
816 {
817         if (use_booktabs)
818                 return false;
819         return cellInfo(cell).right_line;
820 }
821
822
823 bool Tabular::topAlreadyDrawn(idx_type cell) const
824 {
825         row_type row = cellRow(cell);
826         if (row == 0)
827                 return false;
828         idx_type i = cellIndex(row - 1, cellColumn(cell));
829         return !rowTopLine(row) && bottomLine(i);
830 }
831
832
833 bool Tabular::leftAlreadyDrawn(idx_type cell) const
834 {
835         col_type col = cellColumn(cell);
836         if (col == 0)
837                 return false;
838         idx_type i = cellIndex(cellRow(cell), col - 1);
839         return rightLine(i) && !leftLine(cell);
840 }
841
842
843 bool Tabular::isLastRow(idx_type cell) const
844 {
845         return cellRow(cell) == row_info.size() - 1;
846 }
847
848
849 int Tabular::getAdditionalHeight(row_type row) const
850 {
851         if (!row || row >= row_info.size())
852                 return 0;
853
854         int const interline_space = row_info[row - 1].interline_space_default ?
855                 default_line_space :
856                 row_info[row - 1].interline_space.inPixels(width());
857         if (rowTopLine(row) && rowBottomLine(row - 1))
858                 return interline_space + WIDTH_OF_LINE;
859         return interline_space;
860 }
861
862
863 int Tabular::getAdditionalWidth(idx_type cell) const
864 {
865         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
866         if (rightLine(cell) 
867                 && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
868                 return WIDTH_OF_LINE;
869         return 0;
870 }
871
872
873 int Tabular::columnWidth(idx_type cell) const
874 {
875         int w = 0;
876         col_type const span = columnSpan(cell);
877         col_type const col = cellColumn(cell);
878         for(col_type c = col; c < col + span ; ++c)
879                 w += column_info[c].width;
880         return w;
881 }
882
883
884 bool Tabular::updateColumnWidths()
885 {
886         col_type const ncols = column_info.size();
887         row_type const nrows = row_info.size();
888         bool update = false;
889         // for each col get max of single col cells
890         for(col_type c = 0; c < ncols; ++c) {
891                 int new_width = 0;
892                 for(row_type r = 0; r < nrows; ++r) {
893                         idx_type const i = cellIndex(r, c);
894                         if (columnSpan(i) == 1)
895                                 new_width = max(new_width, cellInfo(i).width);
896                 }
897
898                 if (column_info[c].width != new_width) {
899                         column_info[c].width = new_width;
900                         update = true;
901                 }
902         }
903         // update col widths to fit merged cells
904         for(col_type c = 0; c < ncols; ++c)
905                 for(row_type r = 0; r < nrows; ++r) {
906                         idx_type const i = cellIndex(r, c);
907                         int const span = columnSpan(i);
908                         if (span == 1 || c > cellColumn(i))
909                                 continue;
910
911                         int old_width = 0;
912                         for(col_type j = c; j < c + span ; ++j)
913                                 old_width += column_info[j].width;
914
915                         if (cellInfo(i).width > old_width) {
916                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
917                                 update = true;
918                         }
919                 }
920
921         return update;
922 }
923
924
925 int Tabular::width() const
926 {
927         col_type const ncols = column_info.size();
928         int width = 0;
929         for (col_type i = 0; i < ncols; ++i)
930                 width += column_info[i].width;
931         return width;
932 }
933
934
935 void Tabular::setCellWidth(idx_type cell, int new_width)
936 {
937         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
938                 + getAdditionalWidth(cell);
939 }
940
941
942 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
943                               bool onlycolumn)
944 {
945         if (!isMultiColumn(cell) || onlycolumn)
946                 column_info[cellColumn(cell)].alignment = align;
947         if (!onlycolumn)
948                 cellInfo(cell).alignment = align;
949         cellInset(cell).get()->setContentAlignment(align);
950 }
951
952
953 void Tabular::setVAlignment(idx_type cell, VAlignment align,
954                                bool onlycolumn)
955 {
956         if (!isMultiColumn(cell) || onlycolumn)
957                 column_info[cellColumn(cell)].valignment = align;
958         if (!onlycolumn)
959                 cellInfo(cell).valignment = align;
960 }
961
962
963 namespace {
964
965 /**
966  * Allow line and paragraph breaks for fixed width cells or disallow them,
967  * merge cell paragraphs and reset layout to standard for variable width
968  * cells.
969  */
970 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
971 {
972         inset->setAutoBreakRows(fixedWidth);
973         inset->toggleFixedWidth(fixedWidth);
974         if (fixedWidth)
975                 return;
976
977         // merge all paragraphs to one
978         BufferParams const & bp = cur.bv().buffer().params();
979         while (inset->paragraphs().size() > 1)
980                 mergeParagraph(bp, inset->paragraphs(), 0);
981
982         // reset layout
983         cur.push(*inset);
984         // undo information has already been recorded
985         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
986                         bp.documentClass().plainLayoutName());
987         cur.pop();
988 }
989
990 }
991
992
993 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
994                 Length const & width)
995 {
996         col_type const j = cellColumn(cell);
997
998         column_info[j].p_width = width;
999         for (row_type i = 0; i < row_info.size(); ++i) {
1000                 idx_type const cell = cellIndex(i, j);
1001                 // because of multicolumns
1002                 toggleFixedWidth(cur, cellInset(cell).get(),
1003                                  !getPWidth(cell).zero());
1004         }
1005         // cur paragraph can become invalid after paragraphs were merged
1006         if (cur.pit() > cur.lastpit())
1007                 cur.pit() = cur.lastpit();
1008         // cur position can become invalid after newlines were removed
1009         if (cur.pos() > cur.lastpos())
1010                 cur.pos() = cur.lastpos();
1011 }
1012
1013
1014 bool Tabular::setFixedWidth(row_type r, col_type c)
1015 {
1016         bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
1017         if ((!column_info[c].p_width.zero() && !multicol)
1018             || (multicol && !cell_info[r][c].p_width.zero())) {
1019                 cell_info[r][c].inset->toggleFixedWidth(true);
1020                 return true;
1021         }
1022         return false;
1023 }
1024
1025
1026 void Tabular::updateContentAlignment(row_type r, col_type c)
1027 {
1028         cell_info[r][c].inset->setContentAlignment(
1029                 getAlignment(cellIndex(r, c)));
1030 }
1031
1032
1033 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1034                 Length const & width)
1035 {
1036         if (!isMultiColumn(cell))
1037                 return false;
1038
1039         cellInfo(cell).p_width = width;
1040         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1041         // cur paragraph can become invalid after paragraphs were merged
1042         if (cur.pit() > cur.lastpit())
1043                 cur.pit() = cur.lastpit();
1044         // cur position can become invalid after newlines were removed
1045         if (cur.pos() > cur.lastpos())
1046                 cur.pos() = cur.lastpos();
1047         return true;
1048 }
1049
1050
1051 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1052                                  Tabular::Feature what)
1053 {
1054         if (what == SET_SPECIAL_MULTI)
1055                 cellInfo(cell).align_special = special;
1056         else
1057                 column_info[cellColumn(cell)].align_special = special;
1058 }
1059
1060
1061 void Tabular::setAllLines(idx_type cell, bool line)
1062 {
1063         setTopLine(cell, line);
1064         setBottomLine(cell, line);
1065         setRightLine(cell, line);
1066         setLeftLine(cell, line);
1067 }
1068
1069
1070 void Tabular::setTopLine(idx_type i, bool line)
1071 {
1072         cellInfo(i).top_line = line;
1073 }
1074
1075
1076 void Tabular::setBottomLine(idx_type i, bool line)
1077 {
1078         cellInfo(i).bottom_line = line;
1079 }
1080
1081
1082 void Tabular::setLeftLine(idx_type cell, bool line)
1083 {
1084         cellInfo(cell).left_line = line;
1085 }
1086
1087
1088 void Tabular::setRightLine(idx_type cell, bool line)
1089 {
1090         cellInfo(cell).right_line = line;
1091 }
1092
1093 bool Tabular::rowTopLine(row_type r) const
1094 {
1095         idx_type i0 = getFirstCellInRow(r);
1096         idx_type i1 = getLastCellInRow(r);
1097         bool all_rows_set = true;
1098         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1099                 all_rows_set = cellInfo(j).top_line;
1100         return all_rows_set;
1101 }
1102
1103
1104 bool Tabular::rowBottomLine(row_type r) const
1105 {
1106         idx_type i0 = getFirstCellInRow(r);
1107         idx_type i1 = getLastCellInRow(r);
1108         bool all_rows_set = true;
1109         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1110                 all_rows_set = cellInfo(j).bottom_line;
1111         return all_rows_set;
1112 }
1113
1114
1115 bool Tabular::columnLeftLine(col_type c) const
1116 {
1117         if (use_booktabs)
1118                 return false;
1119
1120         int nrows_left = 0;
1121         int total = 0;
1122         row_type const nrows = row_info.size();
1123         for (row_type r = 0; r < nrows; ++r) {
1124                 idx_type i = cellIndex(r, c);
1125                 if (c == cellColumn(i)) {
1126                         ++total;
1127                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1128                         if (cellInfo(i).left_line || right)
1129                                 ++nrows_left;
1130                 }
1131         }
1132         return 2 * nrows_left >= total;
1133 }
1134
1135
1136 bool Tabular::columnRightLine(col_type c) const
1137 {
1138         if (use_booktabs)
1139                 return false;
1140
1141         int nrows_right = 0;
1142         int total = 0;
1143         row_type const nrows = row_info.size();
1144         for (row_type r = 0; r < nrows; ++r) {
1145                 idx_type i = cellIndex(r, c);
1146                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1147                         ++total;
1148                         bool left = c + 1 < column_info.size() 
1149                                 && cellInfo(cellIndex(r, c + 1)).left_line
1150                                 || c + 1 == column_info.size();
1151                         if (cellInfo(i).right_line && left)
1152                                 ++nrows_right;
1153                 }
1154         }
1155         return 2 * nrows_right >= total;
1156 }
1157
1158
1159 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1160 {
1161         if (!onlycolumn && isMultiColumn(cell))
1162                 return cellInfo(cell).alignment;
1163         return column_info[cellColumn(cell)].alignment;
1164 }
1165
1166
1167 Tabular::VAlignment
1168 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1169 {
1170         if (!onlycolumn && isMultiColumn(cell))
1171                 return cellInfo(cell).valignment;
1172         return column_info[cellColumn(cell)].valignment;
1173 }
1174
1175
1176 Length const Tabular::getPWidth(idx_type cell) const
1177 {
1178         if (isMultiColumn(cell))
1179                 return cellInfo(cell).p_width;
1180         return column_info[cellColumn(cell)].p_width;
1181 }
1182
1183
1184 int Tabular::cellWidth(idx_type cell) const
1185 {
1186         return cellInfo(cell).width;
1187 }
1188
1189
1190 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1191 {
1192         int x = 0;
1193
1194         switch (getAlignment(cell)) {
1195         case LYX_ALIGN_CENTER:
1196                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1197                 break;
1198         case LYX_ALIGN_RIGHT:
1199                 x += columnWidth(cell) - cellWidth(cell);
1200                 // + getAdditionalWidth(cell);
1201                 break;
1202         default:
1203                 // LYX_ALIGN_LEFT: nothing :-)
1204                 break;
1205         }
1206
1207         // the LaTeX Way :-(
1208         x += WIDTH_OF_LINE;
1209         return x;
1210 }
1211
1212
1213 bool Tabular::isFirstCellInRow(idx_type cell) const
1214 {
1215         return cellColumn(cell) == 0;
1216 }
1217
1218
1219 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1220 {
1221         if (row > row_info.size() - 1)
1222                 row = row_info.size() - 1;
1223         return cell_info[row][0].cellno;
1224 }
1225
1226
1227 bool Tabular::isLastCellInRow(idx_type cell) const
1228 {
1229         return cellRightColumn(cell) == column_info.size() - 1;
1230 }
1231
1232
1233 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1234 {
1235         if (row > row_info.size() - 1)
1236                 row = row_info.size() - 1;
1237         return cell_info[row][column_info.size() - 1].cellno;
1238 }
1239
1240
1241 Tabular::row_type Tabular::cellRow(idx_type cell) const
1242 {
1243         if (cell >= numberofcells)
1244                 return row_info.size() - 1;
1245         if (cell == npos)
1246                 return 0;
1247         return rowofcell[cell];
1248 }
1249
1250
1251 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1252 {
1253         if (cell >= numberofcells)
1254                 return column_info.size() - 1;
1255         if (cell == npos)
1256                 return 0;       
1257         return columnofcell[cell];
1258 }
1259
1260
1261 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1262 {
1263         row_type const row = cellRow(cell);
1264         col_type column = cellColumn(cell);
1265         while (column < column_info.size() - 1 &&
1266                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1267                 ++column;
1268         return column;
1269 }
1270
1271
1272 void Tabular::write(ostream & os) const
1273 {
1274         // header line
1275         os << "<lyxtabular"
1276            << write_attribute("version", 3)
1277            << write_attribute("rows", row_info.size())
1278            << write_attribute("columns", column_info.size())
1279            << ">\n";
1280         // global longtable options
1281         os << "<features"
1282            << write_attribute("rotate", rotate)
1283            << write_attribute("booktabs", use_booktabs)
1284            << write_attribute("islongtable", is_long_tabular)
1285            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1286            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1287            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1288            << write_attribute("headTopDL", endhead.topDL)
1289            << write_attribute("headBottomDL", endhead.bottomDL)
1290            << write_attribute("footTopDL", endfoot.topDL)
1291            << write_attribute("footBottomDL", endfoot.bottomDL)
1292            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1293            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1294            << write_attribute("lastFootEmpty", endlastfoot.empty)
1295            << ">\n";
1296         for (col_type j = 0; j < column_info.size(); ++j) {
1297                 os << "<column"
1298                    << write_attribute("alignment", column_info[j].alignment)
1299                    << write_attribute("valignment", column_info[j].valignment)
1300                    << write_attribute("width", column_info[j].p_width.asString())
1301                    << write_attribute("special", column_info[j].align_special)
1302                    << ">\n";
1303         }
1304         for (row_type i = 0; i < row_info.size(); ++i) {
1305                 static const string def("default");
1306                 os << "<row";
1307                 if (row_info[i].top_space_default)
1308                         os << write_attribute("topspace", def);
1309                 else
1310                         os << write_attribute("topspace", row_info[i].top_space);
1311                 if (row_info[i].bottom_space_default)
1312                         os << write_attribute("bottomspace", def);
1313                 else
1314                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1315                 if (row_info[i].interline_space_default)
1316                         os << write_attribute("interlinespace", def);
1317                 else
1318                         os << write_attribute("interlinespace", row_info[i].interline_space);
1319                 os << write_attribute("endhead", row_info[i].endhead)
1320                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1321                    << write_attribute("endfoot", row_info[i].endfoot)
1322                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1323                    << write_attribute("newpage", row_info[i].newpage)
1324                    << write_attribute("caption", row_info[i].caption)
1325                    << ">\n";
1326                 for (col_type j = 0; j < column_info.size(); ++j) {
1327                         os << "<cell"
1328                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1329                            << write_attribute("alignment", cell_info[i][j].alignment)
1330                            << write_attribute("valignment", cell_info[i][j].valignment)
1331                            << write_attribute("topline", cell_info[i][j].top_line)
1332                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1333                            << write_attribute("leftline", cell_info[i][j].left_line)
1334                            << write_attribute("rightline", cell_info[i][j].right_line)
1335                            << write_attribute("rotate", cell_info[i][j].rotate)
1336                            << write_attribute("usebox", cell_info[i][j].usebox)
1337                            << write_attribute("width", cell_info[i][j].p_width)
1338                            << write_attribute("special", cell_info[i][j].align_special)
1339                            << ">\n";
1340                         os << "\\begin_inset ";
1341                         cell_info[i][j].inset->write(os);
1342                         os << "\n\\end_inset\n"
1343                            << "</cell>\n";
1344                 }
1345                 os << "</row>\n";
1346         }
1347         os << "</lyxtabular>\n";
1348 }
1349
1350
1351 void Tabular::read(Lexer & lex)
1352 {
1353         string line;
1354         istream & is = lex.getStream();
1355
1356         l_getline(is, line);
1357         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1358                 LASSERT(false, /**/);
1359                 return;
1360         }
1361
1362         int version;
1363         if (!getTokenValue(line, "version", version))
1364                 return;
1365         LASSERT(version >= 2, /**/);
1366
1367         int rows_arg;
1368         if (!getTokenValue(line, "rows", rows_arg))
1369                 return;
1370         int columns_arg;
1371         if (!getTokenValue(line, "columns", columns_arg))
1372                 return;
1373         init(buffer(), rows_arg, columns_arg);
1374         l_getline(is, line);
1375         if (!prefixIs(line, "<features")) {
1376                 lyxerr << "Wrong tabular format (expected <features ...> got"
1377                        << line << ')' << endl;
1378                 return;
1379         }
1380         getTokenValue(line, "rotate", rotate);
1381         getTokenValue(line, "booktabs", use_booktabs);
1382         getTokenValue(line, "islongtable", is_long_tabular);
1383         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1384         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1385         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1386         getTokenValue(line, "headTopDL", endhead.topDL);
1387         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1388         getTokenValue(line, "footTopDL", endfoot.topDL);
1389         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1390         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1391         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1392         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1393
1394         for (col_type j = 0; j < column_info.size(); ++j) {
1395                 l_getline(is,line);
1396                 if (!prefixIs(line,"<column")) {
1397                         lyxerr << "Wrong tabular format (expected <column ...> got"
1398                                << line << ')' << endl;
1399                         return;
1400                 }
1401                 getTokenValue(line, "alignment", column_info[j].alignment);
1402                 getTokenValue(line, "valignment", column_info[j].valignment);
1403                 getTokenValue(line, "width", column_info[j].p_width);
1404                 getTokenValue(line, "special", column_info[j].align_special);
1405         }
1406
1407         for (row_type i = 0; i < row_info.size(); ++i) {
1408                 l_getline(is, line);
1409                 if (!prefixIs(line, "<row")) {
1410                         lyxerr << "Wrong tabular format (expected <row ...> got"
1411                                << line << ')' << endl;
1412                         return;
1413                 }
1414                 getTokenValue(line, "topspace", row_info[i].top_space,
1415                               row_info[i].top_space_default);
1416                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1417                               row_info[i].bottom_space_default);
1418                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1419                               row_info[i].interline_space_default);
1420                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1421                 getTokenValue(line, "endhead", row_info[i].endhead);
1422                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1423                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1424                 getTokenValue(line, "newpage", row_info[i].newpage);
1425                 getTokenValue(line, "caption", row_info[i].caption);
1426                 for (col_type j = 0; j < column_info.size(); ++j) {
1427                         l_getline(is, line);
1428                         if (!prefixIs(line, "<cell")) {
1429                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1430                                        << line << ')' << endl;
1431                                 return;
1432                         }
1433                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1434                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1435                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1436                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1437                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1438                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1439                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1440                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1441                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1442                         getTokenValue(line, "width", cell_info[i][j].p_width);
1443                         setFixedWidth(i,j);
1444                         getTokenValue(line, "special", cell_info[i][j].align_special);
1445                         l_getline(is, line);
1446                         if (prefixIs(line, "\\begin_inset")) {
1447                                 cell_info[i][j].inset->setBuffer(*buffer_);
1448                                 cell_info[i][j].inset->read(lex);
1449                                 l_getline(is, line);
1450                         }
1451                         if (!prefixIs(line, "</cell>")) {
1452                                 lyxerr << "Wrong tabular format (expected </cell> got"
1453                                        << line << ')' << endl;
1454                                 return;
1455                         }
1456                 }
1457                 l_getline(is, line);
1458                 if (!prefixIs(line, "</row>")) {
1459                         lyxerr << "Wrong tabular format (expected </row> got"
1460                                << line << ')' << endl;
1461                         return;
1462                 }
1463         }
1464         while (!prefixIs(line, "</lyxtabular>")) {
1465                 l_getline(is, line);
1466         }
1467         updateIndexes();
1468 }
1469
1470
1471 bool Tabular::isMultiColumn(idx_type cell) const
1472 {
1473         return cellInfo(cell).multicolumn != CELL_NORMAL;
1474 }
1475
1476
1477 bool Tabular::isMultiColumnReal(idx_type cell) const
1478 {
1479         return cellColumn(cell) != cellRightColumn(cell) &&
1480                         cellInfo(cell).multicolumn != CELL_NORMAL;
1481 }
1482
1483
1484 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1485 {
1486         return cell_info[cellRow(cell)][cellColumn(cell)];
1487 }
1488
1489
1490 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1491 {
1492         CellData & cs = cellInfo(cell);
1493         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1494         cs.alignment = column_info[cellColumn(cell)].alignment;
1495         setRightLine(cell, rightLine(cell + number - 1));
1496         for (idx_type i = 1; i < number; ++i) {
1497                 CellData & cs1 = cellInfo(cell + i);
1498                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1499                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1500                 cs1.inset->clear();
1501         }
1502         updateIndexes();
1503 }
1504
1505
1506 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1507 {
1508         row_type const row = cellRow(cell);
1509         col_type const ncols = column_info.size();
1510         idx_type result = 1;
1511         col_type column = cellColumn(cell) + 1;
1512         while (column < ncols && isPartOfMultiColumn(row, column)) {
1513                 ++result;
1514                 ++column;
1515         }
1516         return result;
1517 }
1518
1519
1520 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1521 {
1522         row_type const row = cellRow(cell);
1523         col_type column = cellColumn(cell);
1524
1525         idx_type result = 0;
1526
1527         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1528                 cell_info[row][column].multicolumn = CELL_NORMAL;
1529                 ++column;
1530                 while (column < column_info.size() &&
1531                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1532                 {
1533                         cell_info[row][column].multicolumn = CELL_NORMAL;
1534                         ++column;
1535                         ++result;
1536                 }
1537         }
1538         updateIndexes();
1539         return result;
1540 }
1541
1542
1543 void Tabular::setRotateCell(idx_type cell, bool flag)
1544 {
1545         cellInfo(cell).rotate = flag;
1546 }
1547
1548
1549 bool Tabular::getRotateCell(idx_type cell) const
1550 {
1551         return cellInfo(cell).rotate;
1552 }
1553
1554
1555 bool Tabular::needRotating() const
1556 {
1557         if (rotate)
1558                 return true;
1559         for (row_type i = 0; i < row_info.size(); ++i)
1560                 for (col_type j = 0; j < column_info.size(); ++j)
1561                         if (cell_info[i][j].rotate)
1562                                 return true;
1563         return false;
1564 }
1565
1566
1567 bool Tabular::isLastCell(idx_type cell) const
1568 {
1569         if (cell + 1 < numberofcells)
1570                 return false;
1571         return true;
1572 }
1573
1574
1575 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1576 {
1577         if (cellRow(cell) > 0)
1578                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1579         return cell;
1580 }
1581
1582
1583 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1584 {
1585         if (cellRow(cell) + 1 < row_info.size())
1586                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1587         return cell;
1588 }
1589
1590
1591 Tabular::idx_type Tabular::cellIndex(row_type row,
1592                                                col_type column) const
1593 {
1594         BOOST_ASSERT(column != npos && column < column_info.size()
1595                 && row != npos && row < row_info.size());
1596         return cell_info[row][column].cellno;
1597 }
1598
1599
1600 void Tabular::setUsebox(idx_type cell, BoxType type)
1601 {
1602         cellInfo(cell).usebox = type;
1603 }
1604
1605
1606 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1607 // adds line breaks, see bug 4886.
1608 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1609 {
1610         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1611                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1612                 return BOX_NONE;
1613         if (cellInfo(cell).usebox > 1)
1614                 return cellInfo(cell).usebox;
1615         return useParbox(cell);
1616 }
1617
1618
1619 ///
1620 //  This are functions used for the longtable support
1621 ///
1622 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1623                            bool first)
1624 {
1625         if (first) {
1626                 endfirsthead = hd;
1627                 if (hd.set)
1628                         row_info[row].endfirsthead = flag;
1629         } else {
1630                 endhead = hd;
1631                 if (hd.set)
1632                         row_info[row].endhead = flag;
1633         }
1634 }
1635
1636
1637 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1638 {
1639         hd = endhead;
1640         hd.set = haveLTHead();
1641         return row_info[row].endhead;
1642 }
1643
1644
1645 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1646 {
1647         hd = endfirsthead;
1648         hd.set = haveLTFirstHead();
1649         return row_info[row].endfirsthead;
1650 }
1651
1652
1653 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1654                            bool last)
1655 {
1656         if (last) {
1657                 endlastfoot = fd;
1658                 if (fd.set)
1659                         row_info[row].endlastfoot = flag;
1660         } else {
1661                 endfoot = fd;
1662                 if (fd.set)
1663                         row_info[row].endfoot = flag;
1664         }
1665 }
1666
1667
1668 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1669 {
1670         fd = endfoot;
1671         fd.set = haveLTFoot();
1672         return row_info[row].endfoot;
1673 }
1674
1675
1676 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1677 {
1678         fd = endlastfoot;
1679         fd.set = haveLTLastFoot();
1680         return row_info[row].endlastfoot;
1681 }
1682
1683
1684 void Tabular::setLTNewPage(row_type row, bool what)
1685 {
1686         row_info[row].newpage = what;
1687 }
1688
1689
1690 bool Tabular::getLTNewPage(row_type row) const
1691 {
1692         return row_info[row].newpage;
1693 }
1694
1695
1696 bool Tabular::haveLTHead() const
1697 {
1698         for (row_type i = 0; i < row_info.size(); ++i)
1699                 if (row_info[i].endhead)
1700                         return true;
1701         return false;
1702 }
1703
1704
1705 bool Tabular::haveLTFirstHead() const
1706 {
1707         if (endfirsthead.empty)
1708                 return false;
1709         for (row_type i = 0; i < row_info.size(); ++i)
1710                 if (row_info[i].endfirsthead)
1711                         return true;
1712         return false;
1713 }
1714
1715
1716 bool Tabular::haveLTFoot() const
1717 {
1718         for (row_type i = 0; i < row_info.size(); ++i)
1719                 if (row_info[i].endfoot)
1720                         return true;
1721         return false;
1722 }
1723
1724
1725 bool Tabular::haveLTLastFoot() const
1726 {
1727         if (endlastfoot.empty)
1728                 return false;
1729         for (row_type i = 0; i < row_info.size(); ++i)
1730                 if (row_info[i].endlastfoot)
1731                         return true;
1732         return false;
1733 }
1734
1735
1736 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1737 {
1738         idx_type i = getFirstCellInRow(row);
1739         if (what) {
1740                 setMultiColumn(i, column_info.size());
1741                 setTopLine(i, false);
1742                 setBottomLine(i, false);
1743                 setLeftLine(i, false);
1744                 setRightLine(i, false);
1745         } else
1746                 unsetMultiColumn(i);
1747         row_info[row].caption = what;
1748         return i;
1749 }
1750
1751
1752 bool Tabular::ltCaption(row_type row) const
1753 {
1754         return row_info[row].caption;
1755 }
1756
1757
1758 // end longtable support functions
1759
1760 void Tabular::setRowAscent(row_type row, int height)
1761 {
1762         if (row >= row_info.size() || row_info[row].ascent == height)
1763                 return;
1764         row_info[row].ascent = height;
1765 }
1766
1767
1768 void Tabular::setRowDescent(row_type row, int height)
1769 {
1770         if (row >= row_info.size() || row_info[row].descent == height)
1771                 return;
1772         row_info[row].descent = height;
1773 }
1774
1775
1776 int Tabular::rowAscent(row_type row) const
1777 {
1778         if (row >= row_info.size())
1779                 return 0;
1780         return row_info[row].ascent;
1781 }
1782
1783
1784 int Tabular::rowDescent(row_type row) const
1785 {
1786         LASSERT(row < row_info.size(), /**/);
1787         return row_info[row].descent;
1788 }
1789
1790
1791 int Tabular::height() const
1792 {
1793         int height = 0;
1794         for (row_type row = 0; row < row_info.size(); ++row)
1795                 height += rowAscent(row) + rowDescent(row) +
1796                         getAdditionalHeight(row);
1797         return height;
1798 }
1799
1800
1801 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1802 {
1803         LASSERT(row < row_info.size(), /**/);
1804         LASSERT(column < column_info.size(), /**/);
1805         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1806 }
1807
1808
1809 int Tabular::TeXTopHLine(odocstream & os, row_type row) const
1810 {
1811         // we only output complete row lines and the 1st row here, the rest
1812         // is done in Tabular::TeXBottomHLine(...)
1813
1814         // get for each column the topline (if any)
1815         col_type const ncols = column_info.size();
1816         vector<bool> topline;
1817         int nset = 0;
1818         for (col_type c = 0; c < ncols; ++c) {
1819                 topline.push_back(topLine(cellIndex(row, c)));
1820                 if (topline[c])
1821                         ++nset;
1822         }
1823
1824         // do nothing if empty first row, or incomplete row line after
1825         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols))
1826                 return 0;
1827
1828         // only output complete row lines and the 1st row's clines
1829         if (nset == ncols) {
1830                 if (use_booktabs) {
1831                         os << (row == 0 ? "\\toprule " : "\\midrule ");
1832                 } else {
1833                         os << "\\hline ";
1834                 }
1835         } else if (row == 0) {
1836                 for (col_type c = 0; c < ncols; ++c) {
1837                         if (topline[c]) {
1838                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 << '-';
1839                                 // get to last column of line span
1840                                 while (c < ncols && topline[c])
1841                                         ++c;
1842                                 os << c << "} ";
1843                         }
1844                 }
1845         }
1846         os << "\n";
1847         return 1;
1848 }
1849
1850
1851 int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
1852 {
1853         // we output bottomlines of row r and the toplines of row r+1
1854         // if the latter do not span the whole tabular
1855
1856         // get the bottomlines of row r, and toplines in next row
1857         bool lastrow = row == row_info.size() - 1;
1858         col_type const ncols = column_info.size();
1859         vector<bool> bottomline, topline;
1860         bool nextrowset = true;
1861         for (col_type c = 0; c < ncols; ++c) {
1862                 bottomline.push_back(bottomLine(cellIndex(row, c)));
1863                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
1864                 nextrowset &= topline[c];
1865         }
1866
1867         // combine this row's bottom lines and next row's toplines if necessary
1868         int nset = 0;
1869         for (col_type c = 0; c < ncols; ++c) {
1870                 if (!nextrowset)
1871                         bottomline[c] = bottomline[c] || topline[c];
1872                 if (bottomline[c])
1873                         ++nset;
1874         }
1875
1876         // do nothing if empty, OR incomplete row line with a topline in next row
1877         if (nset == 0 || (nextrowset && nset != ncols))
1878                 return 0;
1879
1880         if (nset == ncols) {
1881                 if (use_booktabs)
1882                         os << (lastrow ? "\\bottomrule" : "\\midrule");
1883                 else
1884                         os << "\\hline";
1885         } else {
1886                 for (col_type c = 0; c < ncols; ++c) {
1887                         if (bottomline[c]) {
1888                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1889                                    << c + 1 << '-';
1890                                 // get to last column of line span
1891                                 while (c < ncols && bottomline[c])
1892                                         ++c;
1893                                 os << c << "} ";
1894                         }
1895                 }
1896         }
1897         os << "\n";
1898         return 1;
1899 }
1900
1901
1902 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1903 {
1904         int ret = 0;
1905         row_type const r = cellRow(cell);
1906         if (is_long_tabular && row_info[r].caption)
1907                 return ret;
1908
1909         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1910         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1911         // figure out how to set the lines
1912         // we always set double lines to the right of the cell
1913         col_type const c = cellColumn(cell);
1914         col_type const nextcol = c + columnSpan(cell);
1915         bool colright = columnRightLine(c);
1916         bool colleft = columnLeftLine(c);
1917         bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
1918         bool nextcellleft = nextcol < column_info.size() 
1919                 && leftLine(cellIndex(r, nextcol));
1920         bool coldouble = colright && nextcolleft;
1921         bool celldouble = rightLine(cell) && nextcellleft;
1922         ismulticol = isMultiColumn(cell) 
1923                 || (c == 0 && colleft != leftLine(cell))
1924                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
1925                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
1926                 || (coldouble != celldouble);
1927         if (ismulticol) {
1928                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
1929                 if (c ==0 && leftLine(cell))
1930                         os << '|';
1931                 if (!cellInfo(cell).align_special.empty()) {
1932                         os << cellInfo(cell).align_special;
1933                 } else {
1934                         if (!getPWidth(cell).zero()) {
1935                                 switch (align) {
1936                                 case LYX_ALIGN_LEFT:
1937                                         os << ">{\\raggedright}";
1938                                         break;
1939                                 case LYX_ALIGN_RIGHT:
1940                                         os << ">{\\raggedleft}";
1941                                         break;
1942                                 case LYX_ALIGN_CENTER:
1943                                         os << ">{\\centering}";
1944                                         break;
1945                                 default:
1946                                         break;
1947                                 }
1948                                 switch (valign) {
1949                                 case LYX_VALIGN_TOP:
1950                                         os << 'p';
1951                                         break;
1952                                 case LYX_VALIGN_MIDDLE:
1953                                         os << 'm';
1954                                         break;
1955                                 case LYX_VALIGN_BOTTOM:
1956                                         os << 'b';
1957                                         break;
1958                                 }
1959                                 os << '{'
1960                                    << from_ascii(getPWidth(cell).asLatexString())
1961                                    << '}';
1962                         } else {
1963                                 switch (align) {
1964                                 case LYX_ALIGN_LEFT:
1965                                         os << 'l';
1966                                         break;
1967                                 case LYX_ALIGN_RIGHT:
1968                                         os << 'r';
1969                                         break;
1970                                 default:
1971                                         os << 'c';
1972                                         break;
1973                                 }
1974                         } // end if else !getPWidth
1975                 } // end if else !cellinfo_of_cell
1976                 if (rightLine(cell) || nextcellleft)
1977                         os << '|';
1978                 if (celldouble)
1979                         // add extra vertical line if we want a double one
1980                         os << '|';
1981                 os << "}{";
1982                 }
1983         if (getRotateCell(cell)) {
1984                 os << "\\begin{sideways}\n";
1985                 ++ret;
1986         }
1987         if (getUsebox(cell) == BOX_PARBOX) {
1988                 os << "\\parbox[";
1989                 switch (valign) {
1990                 case LYX_VALIGN_TOP:
1991                         os << 't';
1992                         break;
1993                 case LYX_VALIGN_MIDDLE:
1994                         os << 'c';
1995                         break;
1996                 case LYX_VALIGN_BOTTOM:
1997                         os << 'b';
1998                         break;
1999                 }
2000                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2001                    << "}{";
2002         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2003                 os << "\\begin{minipage}[";
2004                 switch (valign) {
2005                 case LYX_VALIGN_TOP:
2006                         os << 't';
2007                         break;
2008                 case LYX_VALIGN_MIDDLE:
2009                         os << 'm';
2010                         break;
2011                 case LYX_VALIGN_BOTTOM:
2012                         os << 'b';
2013                         break;
2014                 }
2015                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2016                    << "}\n";
2017                 ++ret;
2018         }
2019         return ret;
2020 }
2021
2022
2023 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
2024 {
2025         int ret = 0;
2026         row_type const r = cellRow(cell);
2027         if (is_long_tabular && row_info[r].caption)
2028                 return ret;
2029
2030         // usual cells
2031         if (getUsebox(cell) == BOX_PARBOX)
2032                 os << '}';
2033         else if (getUsebox(cell) == BOX_MINIPAGE) {
2034                 os << "%\n\\end{minipage}";
2035                 ret += 2;
2036         }
2037         if (getRotateCell(cell)) {
2038                 os << "%\n\\end{sideways}";
2039                 ++ret;
2040         }
2041         if (ismulticol) {
2042                 os << '}';
2043         }
2044         return ret;
2045 }
2046
2047
2048 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
2049                                          OutputParams const & runparams) const
2050 {
2051         if (!is_long_tabular)
2052                 return 0;
2053
2054         int ret = 0;
2055         // output header info
2056         if (haveLTHead()) {
2057                 if (endhead.topDL) {
2058                         os << "\\hline\n";
2059                         ++ret;
2060                 }
2061                 for (row_type i = 0; i < row_info.size(); ++i) {
2062                         if (row_info[i].endhead) {
2063                                 ret += TeXRow(os, i, runparams);
2064                         }
2065                 }
2066                 if (endhead.bottomDL) {
2067                         os << "\\hline\n";
2068                         ++ret;
2069                 }
2070                 os << "\\endhead\n";
2071                 ++ret;
2072                 if (endfirsthead.empty) {
2073                         os << "\\endfirsthead\n";
2074                         ++ret;
2075                 }
2076         }
2077         // output firstheader info
2078         if (haveLTFirstHead()) {
2079                 if (endfirsthead.topDL) {
2080                         os << "\\hline\n";
2081                         ++ret;
2082                 }
2083                 for (row_type i = 0; i < row_info.size(); ++i) {
2084                         if (row_info[i].endfirsthead) {
2085                                 ret += TeXRow(os, i, runparams);
2086                         }
2087                 }
2088                 if (endfirsthead.bottomDL) {
2089                         os << "\\hline\n";
2090                         ++ret;
2091                 }
2092                 os << "\\endfirsthead\n";
2093                 ++ret;
2094         }
2095         // output footer info
2096         if (haveLTFoot()) {
2097                 if (endfoot.topDL) {
2098                         os << "\\hline\n";
2099                         ++ret;
2100                 }
2101                 for (row_type i = 0; i < row_info.size(); ++i) {
2102                         if (row_info[i].endfoot) {
2103                                 ret += TeXRow(os, i, runparams);
2104                         }
2105                 }
2106                 if (endfoot.bottomDL) {
2107                         os << "\\hline\n";
2108                         ++ret;
2109                 }
2110                 os << "\\endfoot\n";
2111                 ++ret;
2112                 if (endlastfoot.empty) {
2113                         os << "\\endlastfoot\n";
2114                         ++ret;
2115                 }
2116         }
2117         // output lastfooter info
2118         if (haveLTLastFoot()) {
2119                 if (endlastfoot.topDL) {
2120                         os << "\\hline\n";
2121                         ++ret;
2122                 }
2123                 for (row_type i = 0; i < row_info.size(); ++i) {
2124                         if (row_info[i].endlastfoot) {
2125                                 ret += TeXRow(os, i, runparams);
2126                         }
2127                 }
2128                 if (endlastfoot.bottomDL) {
2129                         os << "\\hline\n";
2130                         ++ret;
2131                 }
2132                 os << "\\endlastfoot\n";
2133                 ++ret;
2134         }
2135         return ret;
2136 }
2137
2138
2139 bool Tabular::isValidRow(row_type row) const
2140 {
2141         if (!is_long_tabular)
2142                 return true;
2143         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2144                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2145 }
2146
2147
2148 int Tabular::TeXRow(odocstream & os, row_type i,
2149                        OutputParams const & runparams) const
2150 {
2151         idx_type cell = cellIndex(i, 0);
2152         int ret = TeXTopHLine(os, i);
2153         if (row_info[i].top_space_default) {
2154                 if (use_booktabs)
2155                         os << "\\addlinespace\n";
2156                 else
2157                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2158                 ++ret;
2159         } else if(!row_info[i].top_space.zero()) {
2160                 if (use_booktabs)
2161                         os << "\\addlinespace["
2162                            << from_ascii(row_info[i].top_space.asLatexString())
2163                            << "]\n";
2164                 else {
2165                         os << "\\noalign{\\vskip"
2166                            << from_ascii(row_info[i].top_space.asLatexString())
2167                            << "}\n";
2168                 }
2169                 ++ret;
2170         }
2171         bool ismulticol = false;
2172         for (col_type j = 0; j < column_info.size(); ++j) {
2173                 if (isPartOfMultiColumn(i, j))
2174                         continue;
2175                 ret += TeXCellPreamble(os, cell, ismulticol);
2176                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2177
2178                 Paragraph const & par = inset->paragraphs().front();
2179                 bool rtl = par.isRTL(buffer().params())
2180                         && !par.empty()
2181                         && getPWidth(cell).zero();
2182
2183                 if (rtl) {
2184                         string const lang =
2185                                 par.getParLanguage(buffer().params())->lang();
2186                         if (lang == "farsi")
2187                                 os << "\\textFR{";
2188                         else if (lang == "arabic_arabi")
2189                                 os << "\\textAR{";
2190                         // currently, remaning RTL languages are
2191                         // arabic_arabtex and hebrew
2192                         else
2193                                 os << "\\R{";
2194                 }
2195                 // pass to the OutputParams that we are in a cell and
2196                 // which alignment we have set.
2197                 // InsetNewline needs this context information.
2198                 OutputParams newrp = runparams;
2199                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2200                                     ? OutputParams::PLAIN
2201                                     : OutputParams::ALIGNED;
2202                 ret += inset->latex(os, newrp);
2203                 if (rtl)
2204                         os << '}';
2205
2206                 ret += TeXCellPostamble(os, cell, ismulticol);
2207                 if (!isLastCellInRow(cell)) { // not last cell in row
2208                         os << " & ";
2209                 }
2210                 ++cell;
2211         }
2212         os << "\\tabularnewline";
2213         if (row_info[i].bottom_space_default) {
2214                 if (use_booktabs)
2215                         os << "\\addlinespace";
2216                 else
2217                         os << "[\\doublerulesep]";
2218         } else if (!row_info[i].bottom_space.zero()) {
2219                 if (use_booktabs)
2220                         os << "\\addlinespace";
2221                 os << '['
2222                    << from_ascii(row_info[i].bottom_space.asLatexString())
2223                    << ']';
2224         }
2225         os << '\n';
2226         ++ret;
2227         ret += TeXBottomHLine(os, i);
2228         if (row_info[i].interline_space_default) {
2229                 if (use_booktabs)
2230                         os << "\\addlinespace\n";
2231                 else
2232                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2233                 ++ret;
2234         } else if (!row_info[i].interline_space.zero()) {
2235                 if (use_booktabs)
2236                         os << "\\addlinespace["
2237                            << from_ascii(row_info[i].interline_space.asLatexString())
2238                            << "]\n";
2239                 else
2240                         os << "\\noalign{\\vskip"
2241                            << from_ascii(row_info[i].interline_space.asLatexString())
2242                            << "}\n";
2243                 ++ret;
2244         }
2245         return ret;
2246 }
2247
2248
2249 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2250 {
2251         int ret = 0;
2252
2253         //+---------------------------------------------------------------------
2254         //+                      first the opening preamble                    +
2255         //+---------------------------------------------------------------------
2256
2257         if (rotate) {
2258                 os << "\\begin{sideways}\n";
2259                 ++ret;
2260         }
2261         if (is_long_tabular)
2262                 os << "\\begin{longtable}{";
2263         else
2264                 os << "\\begin{tabular}{";
2265
2266         for (col_type i = 0; i < column_info.size(); ++i) {
2267                 if (columnLeftLine(i))
2268                         os << '|';
2269                 if (!column_info[i].align_special.empty()) {
2270                         os << column_info[i].align_special;
2271                 } else {
2272                         if (!column_info[i].p_width.zero()) {
2273                                 switch (column_info[i].alignment) {
2274                                 case LYX_ALIGN_LEFT:
2275                                         os << ">{\\raggedright}";
2276                                         break;
2277                                 case LYX_ALIGN_RIGHT:
2278                                         os << ">{\\raggedleft}";
2279                                         break;
2280                                 case LYX_ALIGN_CENTER:
2281                                         os << ">{\\centering}";
2282                                         break;
2283                                 case LYX_ALIGN_NONE:
2284                                 case LYX_ALIGN_BLOCK:
2285                                 case LYX_ALIGN_LAYOUT:
2286                                 case LYX_ALIGN_SPECIAL:
2287                                         break;
2288                                 }
2289
2290                                 switch (column_info[i].valignment) {
2291                                 case LYX_VALIGN_TOP:
2292                                         os << 'p';
2293                                         break;
2294                                 case LYX_VALIGN_MIDDLE:
2295                                         os << 'm';
2296                                         break;
2297                                 case LYX_VALIGN_BOTTOM:
2298                                         os << 'b';
2299                                         break;
2300                         }
2301                                 os << '{'
2302                                    << from_ascii(column_info[i].p_width.asLatexString())
2303                                    << '}';
2304                         } else {
2305                                 switch (column_info[i].alignment) {
2306                                 case LYX_ALIGN_LEFT:
2307                                         os << 'l';
2308                                         break;
2309                                 case LYX_ALIGN_RIGHT:
2310                                         os << 'r';
2311                                         break;
2312                                 default:
2313                                         os << 'c';
2314                                         break;
2315                                 }
2316                         } // end if else !column_info[i].p_width
2317                 } // end if else !column_info[i].align_special
2318                 if (columnRightLine(i))
2319                         os << '|';
2320         }
2321         os << "}\n";
2322         ++ret;
2323
2324         ret += TeXLongtableHeaderFooter(os, runparams);
2325
2326         //+---------------------------------------------------------------------
2327         //+                      the single row and columns (cells)            +
2328         //+---------------------------------------------------------------------
2329
2330         for (row_type i = 0; i < row_info.size(); ++i) {
2331                 if (isValidRow(i)) {
2332                         ret += TeXRow(os, i, runparams);
2333                         if (is_long_tabular && row_info[i].newpage) {
2334                                 os << "\\newpage\n";
2335                                 ++ret;
2336                         }
2337                 }
2338         }
2339
2340         //+---------------------------------------------------------------------
2341         //+                      the closing of the tabular                    +
2342         //+---------------------------------------------------------------------
2343
2344         if (is_long_tabular)
2345                 os << "\\end{longtable}";
2346         else
2347                 os << "\\end{tabular}";
2348         if (rotate) {
2349                 os << "\n\\end{sideways}";
2350                 ++ret;
2351         }
2352
2353         return ret;
2354 }
2355
2356
2357 int Tabular::docbookRow(odocstream & os, row_type row,
2358                            OutputParams const & runparams) const
2359 {
2360         int ret = 0;
2361         idx_type cell = getFirstCellInRow(row);
2362
2363         os << "<row>\n";
2364         for (col_type j = 0; j < column_info.size(); ++j) {
2365                 if (isPartOfMultiColumn(row, j))
2366                         continue;
2367
2368                 os << "<entry align=\"";
2369                 switch (getAlignment(cell)) {
2370                 case LYX_ALIGN_LEFT:
2371                         os << "left";
2372                         break;
2373                 case LYX_ALIGN_RIGHT:
2374                         os << "right";
2375                         break;
2376                 default:
2377                         os << "center";
2378                         break;
2379                 }
2380
2381                 os << "\" valign=\"";
2382                 switch (getVAlignment(cell)) {
2383                 case LYX_VALIGN_TOP:
2384                         os << "top";
2385                         break;
2386                 case LYX_VALIGN_BOTTOM:
2387                         os << "bottom";
2388                         break;
2389                 case LYX_VALIGN_MIDDLE:
2390                         os << "middle";
2391                 }
2392                 os << '"';
2393
2394                 if (isMultiColumn(cell)) {
2395                         os << " namest=\"col" << j << "\" ";
2396                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2397                 }
2398
2399                 os << '>';
2400                 ret += cellInset(cell)->docbook(os, runparams);
2401                 os << "</entry>\n";
2402                 ++cell;
2403         }
2404         os << "</row>\n";
2405         return ret;
2406 }
2407
2408
2409 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2410 {
2411         int ret = 0;
2412
2413         //+---------------------------------------------------------------------
2414         //+                      first the opening preamble                    +
2415         //+---------------------------------------------------------------------
2416
2417         os << "<tgroup cols=\"" << column_info.size()
2418            << "\" colsep=\"1\" rowsep=\"1\">\n";
2419
2420         for (col_type i = 0; i < column_info.size(); ++i) {
2421                 os << "<colspec colname=\"col" << i << "\" align=\"";
2422                 switch (column_info[i].alignment) {
2423                 case LYX_ALIGN_LEFT:
2424                         os << "left";
2425                         break;
2426                 case LYX_ALIGN_RIGHT:
2427                         os << "right";
2428                         break;
2429                 default:
2430                         os << "center";
2431                         break;
2432                 }
2433                 os << '"';
2434                 if (runparams.flavor == OutputParams::XML)
2435                         os << '/';
2436                 os << ">\n";
2437                 ++ret;
2438         }
2439
2440         //+---------------------------------------------------------------------
2441         //+                      Long Tabular case                             +
2442         //+---------------------------------------------------------------------
2443
2444         // output header info
2445         if (haveLTHead() || haveLTFirstHead()) {
2446                 os << "<thead>\n";
2447                 ++ret;
2448                 for (row_type i = 0; i < row_info.size(); ++i) {
2449                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2450                                 ret += docbookRow(os, i, runparams);
2451                         }
2452                 }
2453                 os << "</thead>\n";
2454                 ++ret;
2455         }
2456         // output footer info
2457         if (haveLTFoot() || haveLTLastFoot()) {
2458                 os << "<tfoot>\n";
2459                 ++ret;
2460                 for (row_type i = 0; i < row_info.size(); ++i) {
2461                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2462                                 ret += docbookRow(os, i, runparams);
2463                         }
2464                 }
2465                 os << "</tfoot>\n";
2466                 ++ret;
2467         }
2468
2469         //+---------------------------------------------------------------------
2470         //+                      the single row and columns (cells)            +
2471         //+---------------------------------------------------------------------
2472
2473         os << "<tbody>\n";
2474         ++ret;
2475         for (row_type i = 0; i < row_info.size(); ++i) {
2476                 if (isValidRow(i)) {
2477                         ret += docbookRow(os, i, runparams);
2478                 }
2479         }
2480         os << "</tbody>\n";
2481         ++ret;
2482         //+---------------------------------------------------------------------
2483         //+                      the closing of the tabular                    +
2484         //+---------------------------------------------------------------------
2485
2486         os << "</tgroup>";
2487         ++ret;
2488
2489         return ret;
2490 }
2491
2492
2493 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2494                                    vector<unsigned int> const & clen) const
2495 {
2496         idx_type const fcell = getFirstCellInRow(row);
2497         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2498         idx_type tmp = 0;
2499
2500         for (idx_type i = fcell; i < n; ++i) {
2501                 if (topLine(i)) {
2502                         ++tmp;
2503                         break;
2504                 }
2505         }
2506         if (!tmp)
2507                 return false;
2508
2509         char_type ch;
2510         for (idx_type i = fcell; i < n; ++i) {
2511                 if (topLine(i)) {
2512                         if (leftLine(i))
2513                                 os << "+-";
2514                         else
2515                                 os << "--";
2516                         ch = '-';
2517                 } else {
2518                         os << "  ";
2519                         ch = ' ';
2520                 }
2521                 col_type column = cellColumn(i);
2522                 int len = clen[column];
2523                 while (column < column_info.size() - 1
2524                        && isPartOfMultiColumn(row, ++column))
2525                         len += clen[column] + 4;
2526                 os << docstring(len, ch);
2527                 if (topLine(i)) {
2528                         if (rightLine(i))
2529                                 os << "-+";
2530                         else
2531                                 os << "--";
2532                 } else {
2533                         os << "  ";
2534                 }
2535         }
2536         os << endl;
2537         return true;
2538 }
2539
2540
2541 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2542                                       vector<unsigned int> const & clen) const
2543 {
2544         idx_type const fcell = getFirstCellInRow(row);
2545         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2546         idx_type tmp = 0;
2547
2548         for (idx_type i = fcell; i < n; ++i) {
2549                 if (bottomLine(i)) {
2550                         ++tmp;
2551                         break;
2552                 }
2553         }
2554         if (!tmp)
2555                 return false;
2556
2557         char_type ch;
2558         for (idx_type i = fcell; i < n; ++i) {
2559                 if (bottomLine(i)) {
2560                         if (leftLine(i))
2561                                 os << "+-";
2562                         else
2563                                 os << "--";
2564                         ch = '-';
2565                 } else {
2566                         os << "  ";
2567                         ch = ' ';
2568                 }
2569                 col_type column = cellColumn(i);
2570                 int len = clen[column];
2571                 while (column < column_info.size() -1
2572                        && isPartOfMultiColumn(row, ++column))
2573                         len += clen[column] + 4;
2574                 os << docstring(len, ch);
2575                 if (bottomLine(i)) {
2576                         if (rightLine(i))
2577                                 os << "-+";
2578                         else
2579                                 os << "--";
2580                 } else {
2581                         os << "  ";
2582                 }
2583         }
2584         os << endl;
2585         return true;
2586 }
2587
2588
2589 void Tabular::plaintextPrintCell(odocstream & os,
2590                                OutputParams const & runparams,
2591                                idx_type cell, row_type row, col_type column,
2592                                vector<unsigned int> const & clen,
2593                                bool onlydata) const
2594 {
2595         odocstringstream sstr;
2596         cellInset(cell)->plaintext(sstr, runparams);
2597
2598         if (onlydata) {
2599                 os << sstr.str();
2600                 return;
2601         }
2602
2603         if (leftLine(cell))
2604                 os << "| ";
2605         else
2606                 os << "  ";
2607
2608         unsigned int len1 = sstr.str().length();
2609         unsigned int len2 = clen[column];
2610         while (column < column_info.size() -1
2611                && isPartOfMultiColumn(row, ++column))
2612                 len2 += clen[column] + 4;
2613         len2 -= len1;
2614
2615         switch (getAlignment(cell)) {
2616         default:
2617         case LYX_ALIGN_LEFT:
2618                 len1 = 0;
2619                 break;
2620         case LYX_ALIGN_RIGHT:
2621                 len1 = len2;
2622                 len2 = 0;
2623                 break;
2624         case LYX_ALIGN_CENTER:
2625                 len1 = len2 / 2;
2626                 len2 -= len1;
2627                 break;
2628         }
2629
2630         os << docstring(len1, ' ') << sstr.str()
2631            << docstring(len2, ' ');
2632
2633         if (rightLine(cell))
2634                 os << " |";
2635         else
2636                 os << "  ";
2637 }
2638
2639
2640 void Tabular::plaintext(odocstream & os,
2641                            OutputParams const & runparams, int const depth,
2642                            bool onlydata, char_type delim) const
2643 {
2644         // first calculate the width of the single columns
2645         vector<unsigned int> clen(column_info.size());
2646
2647         if (!onlydata) {
2648                 // first all non (real) multicolumn cells!
2649                 for (col_type j = 0; j < column_info.size(); ++j) {
2650                         clen[j] = 0;
2651                         for (row_type i = 0; i < row_info.size(); ++i) {
2652                                 idx_type cell = cellIndex(i, j);
2653                                 if (isMultiColumnReal(cell))
2654                                         continue;
2655                                 odocstringstream sstr;
2656                                 cellInset(cell)->plaintext(sstr, runparams);
2657                                 if (clen[j] < sstr.str().length())
2658                                         clen[j] = sstr.str().length();
2659                         }
2660                 }
2661                 // then all (real) multicolumn cells!
2662                 for (col_type j = 0; j < column_info.size(); ++j) {
2663                         for (row_type i = 0; i < row_info.size(); ++i) {
2664                                 idx_type cell = cellIndex(i, j);
2665                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2666                                         continue;
2667                                 odocstringstream sstr;
2668                                 cellInset(cell)->plaintext(sstr, runparams);
2669                                 int len = int(sstr.str().length());
2670                                 idx_type const n = columnSpan(cell);
2671                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2672                                         len -= clen[k];
2673                                 if (len > int(clen[j + n - 1]))
2674                                         clen[j + n - 1] = len;
2675                         }
2676                 }
2677         }
2678         idx_type cell = 0;
2679         for (row_type i = 0; i < row_info.size(); ++i) {
2680                 if (!onlydata && plaintextTopHLine(os, i, clen))
2681                         os << docstring(depth * 2, ' ');
2682                 for (col_type j = 0; j < column_info.size(); ++j) {
2683                         if (isPartOfMultiColumn(i, j))
2684                                 continue;
2685                         if (onlydata && j > 0)
2686                                 // we don't use operator<< for single UCS4 character.
2687                                 // see explanation in docstream.h
2688                                 os.put(delim);
2689                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2690                         ++cell;
2691                 }
2692                 os << endl;
2693                 if (!onlydata) {
2694                         os << docstring(depth * 2, ' ');
2695                         if (plaintextBottomHLine(os, i, clen))
2696                                 os << docstring(depth * 2, ' ');
2697                 }
2698         }
2699 }
2700
2701
2702 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2703 {
2704         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2705 }
2706
2707
2708 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2709                                                col_type column) const
2710 {
2711         return cell_info[row][column].inset;
2712 }
2713
2714
2715 void Tabular::setCellInset(row_type row, col_type column,
2716                               shared_ptr<InsetTableCell> ins) const
2717 {
2718         CellData & cd = cell_info[row][column];
2719         cd.inset = ins;
2720 }
2721
2722
2723 void Tabular::validate(LaTeXFeatures & features) const
2724 {
2725         features.require("NeedTabularnewline");
2726         if (use_booktabs)
2727                 features.require("booktabs");
2728         if (is_long_tabular)
2729                 features.require("longtable");
2730         if (needRotating())
2731                 features.require("rotating");
2732         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2733                 if (getVAlignment(cell) != LYX_VALIGN_TOP
2734                     || !getPWidth(cell).zero())
2735                         features.require("array");
2736                 cellInset(cell)->validate(features);
2737         }
2738 }
2739
2740
2741 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2742 {
2743         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2744         ParagraphList::const_iterator cit = parlist.begin();
2745         ParagraphList::const_iterator end = parlist.end();
2746
2747         for (; cit != end; ++cit)
2748                 for (int i = 0; i < cit->size(); ++i)
2749                         if (cit->isNewline(i))
2750                                 return BOX_PARBOX;
2751
2752         return BOX_NONE;
2753 }
2754
2755
2756 /////////////////////////////////////////////////////////////////////
2757 //
2758 // InsetTableCell
2759 //
2760 /////////////////////////////////////////////////////////////////////
2761
2762 InsetTableCell::InsetTableCell(Buffer & buf)
2763         : InsetText(buf), isFixedWidth(false),
2764           contentAlign(LYX_ALIGN_CENTER)
2765 {}
2766
2767
2768 bool InsetTableCell::forcePlainLayout(idx_type) const
2769 {
2770         return !isFixedWidth;
2771 }
2772
2773
2774 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2775 {
2776         return isFixedWidth;
2777 }
2778
2779
2780 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2781         FuncStatus & status) const
2782 {
2783         bool enabled;
2784         switch (cmd.action) {
2785         case LFUN_LAYOUT:
2786                 enabled = !forcePlainLayout();
2787                 break;
2788         case LFUN_LAYOUT_PARAGRAPH:
2789                 enabled = allowParagraphCustomization();
2790                 break;
2791         default:
2792                 return InsetText::getStatus(cur, cmd, status);
2793         }
2794         status.setEnabled(enabled);
2795         return true;
2796 }
2797
2798 docstring InsetTableCell::asString(bool intoInsets) 
2799 {
2800         docstring retval;
2801         if (paragraphs().empty())
2802                 return retval;
2803         ParagraphList::const_iterator it = paragraphs().begin();
2804         ParagraphList::const_iterator en = paragraphs().end();
2805         bool first = true;
2806         for (; it != en; ++it) {
2807                 if (!first)
2808                         retval += "\n";
2809                 else
2810                         first = false;
2811                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
2812         }
2813         return retval;
2814 }
2815
2816
2817
2818 /////////////////////////////////////////////////////////////////////
2819 //
2820 // InsetTabular
2821 //
2822 /////////////////////////////////////////////////////////////////////
2823
2824 InsetTabular::InsetTabular(Buffer & buf, row_type rows,
2825                            col_type columns)
2826         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2827         rowselect_(false), colselect_(false)
2828 {
2829         setBuffer(buf); // FIXME: remove later
2830 }
2831
2832
2833 InsetTabular::InsetTabular(InsetTabular const & tab)
2834         : Inset(tab), tabular(tab.tabular),  scx_(0)
2835 {
2836 }
2837
2838
2839 InsetTabular::~InsetTabular()
2840 {
2841         hideDialogs("tabular", this);
2842 }
2843
2844
2845 void InsetTabular::setBuffer(Buffer & buf)
2846 {
2847         tabular.setBuffer(buf);
2848         Inset::setBuffer(buf);
2849 }
2850
2851
2852 bool InsetTabular::insetAllowed(InsetCode code) const
2853 {
2854         if (code == MATHMACRO_CODE)
2855                 return false;
2856
2857         return true;
2858 }
2859
2860
2861 void InsetTabular::write(ostream & os) const
2862 {
2863         os << "Tabular" << endl;
2864         tabular.write(os);
2865 }
2866
2867
2868 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
2869 {
2870         // FIXME: depending on the selection state, we could offer a different menu.
2871         return from_ascii("context-tabular");
2872 }
2873
2874
2875 void InsetTabular::read(Lexer & lex)
2876 {
2877         //bool const old_format = (lex.getString() == "\\LyXTable");
2878
2879         tabular.read(lex);
2880
2881         //if (old_format)
2882         //      return;
2883
2884         lex.next();
2885         string token = lex.getString();
2886         while (lex && token != "\\end_inset") {
2887                 lex.next();
2888                 token = lex.getString();
2889         }
2890         if (!lex)
2891                 lex.printError("Missing \\end_inset at this point. ");
2892 }
2893
2894
2895 int InsetTabular::rowFromY(Cursor & cur, int y) const
2896 {
2897         // top y coordinate of tabular
2898         int h = yo(cur.bv()) - tabular.rowAscent(0);
2899         size_t nrows = tabular.row_info.size();
2900         row_type r = 0;
2901         for (; r < nrows && y > h; ++r) {
2902                 h += tabular.rowAscent(r);
2903                 h += tabular.rowDescent(r);
2904                 h += tabular.getAdditionalHeight(r);
2905         }
2906         return r - 1;
2907 }
2908
2909
2910 int InsetTabular::columnFromX(Cursor & cur, int x) const
2911 {
2912         // left x coordinate of tabular
2913         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
2914         size_t ncols = tabular.column_info.size();
2915         col_type c = 0;
2916         for (; c < ncols && x > w; ++c)
2917                 w += tabular.columnWidth(c);
2918         return c - 1;
2919 }
2920
2921
2922 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2923 {
2924         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2925         //      mi.base.textwidth << "\n";
2926         if (!mi.base.bv) {
2927                 LYXERR0("need bv");
2928                 LASSERT(false, /**/);
2929         }
2930
2931         row_type i = 0;
2932         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
2933                 int maxAsc = 0;
2934                 int maxDesc = 0;
2935                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
2936                         if (tabular.isPartOfMultiColumn(i, j))
2937                                 // Multicolumn cell, but not first one
2938                                 continue;
2939                         Dimension dim;
2940                         MetricsInfo m = mi;
2941                         Length p_width;
2942                         if (tabular.cell_info[i][j].multicolumn ==
2943                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2944                                 p_width = tabular.cellInfo(cell).p_width;
2945                         else
2946                                 p_width = tabular.column_info[j].p_width;
2947                         if (!p_width.zero())
2948                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2949                         tabular.cellInset(cell)->metrics(m, dim);
2950                         if (!p_width.zero())
2951                                 dim.wid = m.base.textwidth;
2952                         tabular.setCellWidth(cell, dim.wid);
2953                         maxAsc  = max(maxAsc, dim.asc);
2954                         maxDesc = max(maxDesc, dim.des);
2955                         ++cell;
2956                 }
2957                 int const top_space = tabular.row_info[i].top_space_default ?
2958                         default_line_space :
2959                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2960                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2961                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2962                         default_line_space :
2963                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2964                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2965         }
2966         tabular.updateColumnWidths();
2967         dim.asc = tabular.rowAscent(0);
2968         dim.des = tabular.height() - dim.asc;
2969         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
2970 }
2971
2972
2973 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
2974 {
2975         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
2976         BufferView * bv = pi.base.bv;
2977
2978         // FIXME: As the full backrgound is painted in drawSelection(),
2979         // we have no choice but to do a full repaint for the Text cells.
2980         pi.full_repaint = true;
2981
2982         resetPos(bv->cursor());
2983
2984         x += scx_;
2985         x += ADD_TO_TABULAR_WIDTH;
2986
2987         bool const original_drawing_state = pi.pain.isDrawingEnabled();
2988
2989         idx_type idx = 0;
2990         first_visible_cell = Tabular::npos;
2991         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
2992                 int nx = x;
2993                 int const a = tabular.rowAscent(i);
2994                 int const d = tabular.rowDescent(i);
2995                 idx = tabular.cellIndex(i, 0);
2996                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
2997                         if (tabular.isPartOfMultiColumn(i, j))
2998                                 continue;
2999                         if (first_visible_cell == Tabular::npos)
3000                                 first_visible_cell = idx;
3001
3002                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
3003                         // Cache the Inset position.
3004                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
3005                         if (nx + tabular.columnWidth(idx) < 0
3006                             || nx > bv->workWidth()
3007                             || y + d < 0
3008                             || y - a > bv->workHeight()) {
3009                                 pi.pain.setDrawingEnabled(false);
3010                                 cell(idx)->draw(pi, cx, y);
3011                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3012                                 pi.pain.setDrawingEnabled(original_drawing_state);
3013                         } else {
3014                                 cell(idx)->draw(pi, cx, y);
3015                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
3016                         }
3017                         nx += tabular.columnWidth(idx);
3018                         ++idx;
3019                 }
3020
3021                 if (i + 1 < tabular.row_info.size())
3022                         y += d + tabular.rowAscent(i + 1) +
3023                                 tabular.getAdditionalHeight(i + 1);
3024         }
3025 }
3026
3027
3028 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3029 {
3030         Cursor & cur = pi.base.bv->cursor();
3031
3032         x += scx_ + ADD_TO_TABULAR_WIDTH;
3033
3034         // FIXME: it is wrong to completely paint the background
3035         // if we want to do single row painting.
3036
3037         // Paint background of current tabular
3038         int const w = tabular.width();
3039         int const h = tabular.height();
3040         int yy = y - tabular.rowAscent(0);
3041         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
3042
3043         if (!cur.selection())
3044                 return;
3045         if (&cur.inset() != this)
3046                 return;
3047
3048         //resetPos(cur);
3049
3050
3051         if (cur.selIsMultiCell()) {
3052                 row_type rs, re;
3053                 col_type cs, ce;
3054                 getSelection(cur, rs, re, cs, ce);
3055                 y -= tabular.rowAscent(0);
3056                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
3057                         int const a = tabular.rowAscent(j);
3058                         int const h = a + tabular.rowDescent(j);
3059                         int xx = x;
3060                         y += tabular.getAdditionalHeight(j);
3061                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
3062                                 if (tabular.isPartOfMultiColumn(j, i))
3063                                         continue;
3064                                 idx_type const cell =
3065                                         tabular.cellIndex(j, i);
3066                                 int const w = tabular.columnWidth(cell);
3067                                 if (i >= cs && i <= ce && j >= rs && j <= re)
3068                                         pi.pain.fillRectangle(xx, y, w, h,
3069                                                               Color_selection);
3070                                 xx += w;
3071                         }
3072                         y += h;
3073                 }
3074
3075         } else {
3076                 x += cellXPos(cur.idx());
3077                 x += tabular.getBeginningOfTextInCell(cur.idx());
3078                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3079         }
3080 }
3081
3082
3083 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3084                                  row_type row, idx_type cell, bool erased) const
3085 {
3086         int x2 = x + tabular.columnWidth(cell);
3087         bool on_off = false;
3088         ColorCode col = Color_tabularline;
3089         ColorCode onoffcol = Color_tabularonoffline;
3090
3091         if (erased) {
3092                 col = Color_deletedtext;
3093                 onoffcol = Color_deletedtext;
3094         }
3095
3096         if (!tabular.topAlreadyDrawn(cell)) {
3097                 on_off = !tabular.topLine(cell);
3098                 pain.line(x, y - tabular.rowAscent(row),
3099                           x2, y -  tabular.rowAscent(row),
3100                           on_off ? onoffcol : col,
3101                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3102         }
3103         on_off = !tabular.bottomLine(cell);
3104         pain.line(x, y + tabular.rowDescent(row),
3105                   x2, y + tabular.rowDescent(row),
3106                   on_off ? onoffcol : col,
3107                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3108         if (!tabular.leftAlreadyDrawn(cell)) {
3109                 on_off = !tabular.leftLine(cell);
3110                 pain.line(x, y -  tabular.rowAscent(row),
3111                           x, y +  tabular.rowDescent(row),
3112                           on_off ? onoffcol : col,
3113                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3114         }
3115         on_off = !tabular.rightLine(cell);
3116         pain.line(x2 - tabular.getAdditionalWidth(cell),
3117                   y -  tabular.rowAscent(row),
3118                   x2 - tabular.getAdditionalWidth(cell),
3119                   y +  tabular.rowDescent(row),
3120                   on_off ? onoffcol : col,
3121                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3122 }
3123
3124
3125 docstring InsetTabular::editMessage() const
3126 {
3127         return _("Opened table");
3128 }
3129
3130
3131 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3132 {
3133         //lyxerr << "InsetTabular::edit: " << this << endl;
3134         cur.finishUndo();
3135         cur.selection() = false;
3136         cur.push(*this);
3137         if (front) {
3138                 if (isRightToLeft(cur))
3139                         cur.idx() = tabular.getLastCellInRow(0);
3140                 else
3141                         cur.idx() = 0;
3142                 cur.pit() = 0;
3143                 cur.pos() = 0;
3144         } else {
3145                 if (isRightToLeft(cur))
3146                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3147                 else
3148                         cur.idx() = tabular.numberofcells - 1;
3149                 cur.pit() = 0;
3150                 cur.pos() = cur.lastpos(); // FIXME crude guess
3151         }
3152         // FIXME: this accesses the position cache before it is initialized
3153         //resetPos(cur);
3154         //cur.bv().fitCursor();
3155 }
3156
3157
3158 void InsetTabular::updateLabels(ParIterator const & it)
3159 {
3160         // In a longtable, tell captions what the current float is
3161         Counters & cnts = buffer().params().documentClass().counters();
3162         string const saveflt = cnts.current_float();
3163         if (tabular.is_long_tabular)
3164                 cnts.current_float("table");
3165
3166         ParIterator it2 = it;
3167         it2.forwardPos();
3168         size_t const end = it2.nargs();
3169         for ( ; it2.idx() < end; it2.top().forwardIdx())
3170                 lyx::updateLabels(buffer(), it2);
3171
3172         //reset afterwards
3173         if (tabular.is_long_tabular)
3174                 cnts.current_float(saveflt);
3175 }
3176
3177
3178 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3179 {
3180         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3181                              << "\n  cur:" << cur);
3182         CursorSlice sl = cur.top();
3183         Cursor & bvcur = cur.bv().cursor();
3184
3185         switch (cmd.action) {
3186
3187         case LFUN_MOUSE_PRESS: {
3188                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3189                 // select row
3190                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3191                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3192                         row_type r = rowFromY(cur, cmd.y);
3193                         cur.idx() = tabular.getFirstCellInRow(r);
3194                         cur.pos() = 0;
3195                         cur.resetAnchor();
3196                         cur.idx() = tabular.getLastCellInRow(r);
3197                         cur.pos() = cur.lastpos();
3198                         cur.selection() = true;
3199                         bvcur = cur; 
3200                         rowselect_ = true;
3201                         break;
3202                 }
3203                 // select column
3204                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3205                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3206                         || cmd.y > y0 + tabular.height()) {
3207                         col_type c = columnFromX(cur, cmd.x);
3208                         cur.idx() = tabular.cellIndex(0, c);
3209                         cur.pos() = 0;
3210                         cur.resetAnchor();
3211                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3212                         cur.pos() = cur.lastpos();
3213                         cur.selection() = true;
3214                         bvcur = cur; 
3215                         colselect_ = true;
3216                         break;
3217                 }
3218                 // do not reset cursor/selection if we have selected
3219                 // some cells (bug 2715).
3220                 if (cmd.button() == mouse_button::button3
3221                     && &bvcur.selBegin().inset() == this 
3222                     && bvcur.selIsMultiCell()) 
3223                         ;
3224                 else
3225                         // Let InsetTableCell do it
3226                         cell(cur.idx())->dispatch(cur, cmd);
3227                 break;
3228         }
3229         case LFUN_MOUSE_MOTION:
3230                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3231                 if (cmd.button() == mouse_button::button1) {
3232                         // only accept motions to places not deeper nested than the real anchor
3233                         if (!bvcur.anchor_.hasPart(cur)) {
3234                                 cur.undispatched();
3235                                 break;
3236                         }
3237                         // select (additional) row
3238                         if (rowselect_) {
3239                                 row_type r = rowFromY(cur, cmd.y);
3240                                 cur.idx() = tabular.getLastCellInRow(r);
3241                                 // we need to reset the cursor's pit and pos now, as the old ones
3242                                 // may no longer be valid.
3243                                 cur.pit() = 0;
3244                                 cur.pos() = 0;
3245                                 bvcur.setCursor(cur);
3246                                 bvcur.selection() = true;
3247                                 break;
3248                         }
3249                         // select (additional) column
3250                         if (colselect_) {
3251                                 col_type c = columnFromX(cur, cmd.x);
3252                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3253                                 // we need to reset the cursor's pit and pos now, as the old ones
3254                                 // may no longer be valid.
3255                                 cur.pit() = 0;
3256                                 cur.pos() = 0;
3257                                 bvcur.setCursor(cur);
3258                                 bvcur.selection() = true;
3259                                 break;
3260                         }
3261                         // only update if selection changes
3262                         if (bvcur.idx() == cur.idx() &&
3263                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3264                                 cur.noUpdate();
3265                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3266                         bvcur.setCursor(cur);
3267                         bvcur.selection() = true;
3268                         // if this is a multicell selection, we just set the cursor to
3269                         // the beginning of the cell's text.
3270                         if (bvcur.selIsMultiCell()) {
3271                                 bvcur.pit() = 0;
3272                                 bvcur.pos() = 0;
3273                         }
3274                 }
3275                 break;
3276
3277         case LFUN_MOUSE_RELEASE:
3278                 rowselect_ = false;
3279                 colselect_ = false;
3280                 break;
3281
3282         case LFUN_CELL_BACKWARD:
3283                 movePrevCell(cur);
3284                 cur.selection() = false;
3285                 break;
3286
3287         case LFUN_CELL_FORWARD:
3288                 moveNextCell(cur);
3289                 cur.selection() = false;
3290                 break;
3291
3292         case LFUN_CHAR_FORWARD_SELECT:
3293         case LFUN_CHAR_FORWARD:
3294         case LFUN_CHAR_BACKWARD_SELECT:
3295         case LFUN_CHAR_BACKWARD:
3296         case LFUN_CHAR_RIGHT_SELECT:
3297         case LFUN_CHAR_RIGHT:
3298         case LFUN_CHAR_LEFT_SELECT:
3299         case LFUN_CHAR_LEFT: {
3300                 // determine whether we move to next or previous cell, where to enter 
3301                 // the new cell from, and which command to "finish" (i.e., exit the
3302                 // inset) with:
3303                 bool next_cell;
3304                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3305                 FuncCode finish_lfun;
3306
3307                 if (cmd.action == LFUN_CHAR_FORWARD 
3308                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3309                         next_cell = true;
3310                         finish_lfun = LFUN_FINISHED_FORWARD;
3311                 }
3312                 else if (cmd.action == LFUN_CHAR_BACKWARD
3313                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3314                         next_cell = false;
3315                         finish_lfun = LFUN_FINISHED_BACKWARD;
3316                 }
3317                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3318                 // table's direction.
3319                 else {
3320                         bool right = (cmd.action == LFUN_CHAR_RIGHT
3321                                                         || cmd.action == LFUN_CHAR_RIGHT_SELECT);
3322                         next_cell = (isRightToLeft(cur) != right);
3323                         
3324                         if (lyxrc.visual_cursor) {
3325                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3326                         }
3327
3328                         if (right)
3329                                 finish_lfun = LFUN_FINISHED_RIGHT;
3330                         else
3331                                 finish_lfun = LFUN_FINISHED_LEFT;
3332                 }
3333
3334                 // if we don't have a multicell selection...
3335                 if (!cur.selIsMultiCell() ||
3336                   // ...or we're not doing some LFUN_*_SELECT thing, anyway...
3337                     (cmd.action != LFUN_CHAR_FORWARD_SELECT &&
3338                      cmd.action != LFUN_CHAR_BACKWARD_SELECT &&
3339                      cmd.action != LFUN_CHAR_RIGHT_SELECT &&
3340                      cmd.action != LFUN_CHAR_LEFT_SELECT)) {
3341                         // ...try to dispatch to the cell's inset.
3342                         cell(cur.idx())->dispatch(cur, cmd);
3343                         if (cur.result().dispatched()) 
3344                                 break;
3345                 }
3346                 // move to next/prev cell, as appropriate
3347                 // note that we will always do this if we're selecting and we have
3348                 // a multicell selection
3349                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3350                         << " cell from: " << int(entry_from));
3351                 if (next_cell)
3352                         moveNextCell(cur, entry_from);
3353                 else
3354                         movePrevCell(cur, entry_from);
3355                 // if we're exiting the table, call the appropriate FINISHED lfun
3356                 if (sl == cur.top())
3357                         cmd = FuncRequest(finish_lfun);
3358                 else
3359                         cur.dispatched();
3360                 break;
3361
3362         }
3363
3364         case LFUN_DOWN_SELECT:
3365         case LFUN_DOWN:
3366                 cell(cur.idx())->dispatch(cur, cmd);
3367                 cur.dispatched(); // override the cell's decision
3368                 if (sl == cur.top())
3369                         // if our Text didn't do anything to the cursor
3370                         // then we try to put the cursor into the cell below
3371                         // setting also the right targetX.
3372                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3373                                 cur.idx() = tabular.cellBelow(cur.idx());
3374                                 cur.pit() = 0;
3375                                 TextMetrics const & tm =
3376                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3377                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3378                         }
3379                 if (sl == cur.top()) {
3380                         // we trick it to go to forward after leaving the
3381                         // tabular.
3382                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3383                         cur.undispatched();
3384                 }
3385                 break;
3386
3387         case LFUN_UP_SELECT:
3388         case LFUN_UP:
3389                 cell(cur.idx())->dispatch(cur, cmd);
3390                 cur.dispatched(); // override the cell's decision
3391                 if (sl == cur.top())
3392                         // if our Text didn't do anything to the cursor
3393                         // then we try to put the cursor into the cell above
3394                         // setting also the right targetX.
3395                         if (tabular.cellRow(cur.idx()) != 0) {
3396                                 cur.idx() = tabular.cellAbove(cur.idx());
3397                                 cur.pit() = cur.lastpit();
3398                                 Text const * text = cell(cur.idx())->getText(0);
3399                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3400                                 ParagraphMetrics const & pm =
3401                                         tm.parMetrics(cur.lastpit());
3402                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3403                         }
3404                 if (sl == cur.top()) {
3405                         cmd = FuncRequest(LFUN_UP);
3406                         cur.undispatched();
3407                 }
3408                 break;
3409
3410 //      case LFUN_SCREEN_DOWN: {
3411 //              //if (hasSelection())
3412 //              //      cur.selection() = false;
3413 //              col_type const col = tabular.cellColumn(cur.idx());
3414 //              int const t =   cur.bv().top_y() + cur.bv().height();
3415 //              if (t < yo() + tabular.getHeightOfTabular()) {
3416 //                      cur.bv().scrollDocView(t);
3417 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3418 //              } else {
3419 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3420 //              }
3421 //              cur.par() = 0;
3422 //              cur.pos() = 0;
3423 //              break;
3424 //      }
3425 //
3426 //      case LFUN_SCREEN_UP: {
3427 //              //if (hasSelection())
3428 //              //      cur.selection() = false;
3429 //              col_type const col = tabular.cellColumn(cur.idx());
3430 //              int const t =   cur.bv().top_y() + cur.bv().height();
3431 //              if (yo() < 0) {
3432 //                      cur.bv().scrollDocView(t);
3433 //                      if (yo() > 0)
3434 //                              cur.idx() = col;
3435 //                      else
3436 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3437 //              } else {
3438 //                      cur.idx() = col;
3439 //              }
3440 //              cur.par() = cur.lastpar();
3441 //              cur.pos() = cur.lastpos();
3442 //              break;
3443 //      }
3444
3445         case LFUN_LAYOUT_TABULAR:
3446                 cur.bv().showDialog("tabular", params2string(*this), this);
3447                 break;
3448
3449         case LFUN_INSET_DIALOG_UPDATE:
3450                 cur.bv().updateDialog("tabular", params2string(*this));
3451                 break;
3452
3453         case LFUN_TABULAR_FEATURE:
3454                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3455                         cur.undispatched();
3456                 break;
3457
3458         // insert file functions
3459         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3460         case LFUN_FILE_INSERT_PLAINTEXT: {
3461                 // FIXME UNICODE
3462                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3463                         FileName(to_utf8(cmd.argument())));
3464                 if (tmpstr.empty())
3465                         break;
3466                 cur.recordUndoInset(INSERT_UNDO);
3467                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3468                         // content has been replaced,
3469                         // so cursor might be invalid
3470                         cur.pos() = cur.lastpos();
3471                         cur.pit() = cur.lastpit();
3472                         bvcur.setCursor(cur);
3473                 } else
3474                         cur.undispatched();
3475                 break;
3476         }
3477
3478         case LFUN_CUT:
3479                 if (cur.selIsMultiCell()) {
3480                         if (copySelection(cur)) {
3481                                 cur.recordUndoInset(DELETE_UNDO);
3482                                 cutSelection(cur);
3483                         }
3484                 }
3485                 else
3486                         cell(cur.idx())->dispatch(cur, cmd);
3487                 break;
3488
3489         case LFUN_CHAR_DELETE_BACKWARD:
3490         case LFUN_CHAR_DELETE_FORWARD:
3491                 if (cur.selIsMultiCell()) {
3492                         cur.recordUndoInset(DELETE_UNDO);
3493                         cutSelection(cur);
3494                 }
3495                 else
3496                         cell(cur.idx())->dispatch(cur, cmd);
3497                 break;
3498
3499         case LFUN_COPY:
3500                 if (!cur.selection())
3501                         break;
3502                 if (cur.selIsMultiCell()) {
3503                         cur.finishUndo();
3504                         copySelection(cur);
3505                 } else
3506                         cell(cur.idx())->dispatch(cur, cmd);
3507                 break;
3508
3509         case LFUN_CLIPBOARD_PASTE:
3510         case LFUN_PRIMARY_SELECTION_PASTE: {
3511                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3512                         theClipboard().getAsText() :
3513                         theSelection().get();
3514                 if (clip.empty())
3515                         break;
3516                 // pass to InsertPlaintextString, but
3517                 // only if we have multi-cell content
3518                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3519                         cur.recordUndoInset(INSERT_UNDO);
3520                         if (insertPlaintextString(cur.bv(), clip, false)) {
3521                                 // content has been replaced,
3522                                 // so cursor might be invalid
3523                                 cur.pos() = cur.lastpos();
3524                                 cur.pit() = cur.lastpit();
3525                                 bvcur.setCursor(cur);
3526                                 break;
3527                         }
3528                 }
3529                 // Let the cell handle normal text
3530                 cell(cur.idx())->dispatch(cur, cmd);
3531                 break;
3532         }
3533
3534         case LFUN_PASTE:
3535                 if (!tabularStackDirty()) {
3536                         cell(cur.idx())->dispatch(cur, cmd);
3537                         break;
3538                 }
3539                 if (theClipboard().isInternal() ||
3540                     !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
3541                         cur.recordUndoInset(INSERT_UNDO);
3542                         pasteClipboard(cur);
3543                 }
3544                 break;
3545
3546         case LFUN_FONT_EMPH:
3547         case LFUN_FONT_BOLD:
3548         case LFUN_FONT_ROMAN:
3549         case LFUN_FONT_NOUN:
3550         case LFUN_FONT_ITAL:
3551         case LFUN_FONT_FRAK:
3552         case LFUN_FONT_TYPEWRITER:
3553         case LFUN_FONT_SANS:
3554         case LFUN_TEXTSTYLE_APPLY:
3555         case LFUN_TEXTSTYLE_UPDATE:
3556         case LFUN_FONT_SIZE:
3557         case LFUN_FONT_UNDERLINE:
3558         case LFUN_LANGUAGE:
3559         case LFUN_WORD_CAPITALIZE:
3560         case LFUN_WORD_UPCASE:
3561         case LFUN_WORD_LOWCASE:
3562         case LFUN_CHARS_TRANSPOSE:
3563                 if (cur.selIsMultiCell()) {
3564                         row_type rs, re;
3565                         col_type cs, ce;
3566                         getSelection(cur, rs, re, cs, ce);
3567                         Cursor tmpcur = cur;
3568                         for (row_type i = rs; i <= re; ++i) {
3569                                 for (col_type j = cs; j <= ce; ++j) {
3570                                         // cursor follows cell:
3571                                         tmpcur.idx() = tabular.cellIndex(i, j);
3572                                         // select this cell only:
3573                                         tmpcur.pit() = 0;
3574                                         tmpcur.pos() = 0;
3575                                         tmpcur.resetAnchor();
3576                                         tmpcur.pit() = tmpcur.lastpit();
3577                                         tmpcur.pos() = tmpcur.top().lastpos();
3578                                         tmpcur.setCursor(tmpcur);
3579                                         tmpcur.setSelection();
3580                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3581                                 }
3582                         }
3583                         break;
3584                 } else {
3585                         cell(cur.idx())->dispatch(cur, cmd);
3586                         break;
3587                 }
3588         default:
3589                 // we try to handle this event in the insets dispatch function.
3590                 cell(cur.idx())->dispatch(cur, cmd);
3591                 break;
3592         }
3593 }
3594
3595
3596 // function sets an object as defined in func_status.h:
3597 // states OK, Unknown, Disabled, On, Off.
3598 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3599         FuncStatus & status) const
3600 {
3601         switch (cmd.action) {
3602         case LFUN_TABULAR_FEATURE: {
3603                 int action = Tabular::LAST_ACTION;
3604                 int i = 0;
3605                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3606                         string const tmp = tabularFeature[i].feature;
3607                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3608                                 action = tabularFeature[i].action;
3609                                 break;
3610                         }
3611                 }
3612                 if (action == Tabular::LAST_ACTION) {
3613                         status.clear();
3614                         status.unknown(true);
3615                         return true;
3616                 }
3617
3618                 string const argument
3619                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3620
3621                 row_type sel_row_start = 0;
3622                 row_type sel_row_end = 0;
3623                 col_type sel_col_start = 0;
3624                 col_type sel_col_end = 0;
3625                 Tabular::ltType dummyltt;
3626                 bool flag = true;
3627
3628                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3629
3630                 switch (action) {
3631                 case Tabular::SET_PWIDTH:
3632                 case Tabular::SET_MPWIDTH:
3633                 case Tabular::SET_SPECIAL_COLUMN:
3634                 case Tabular::SET_SPECIAL_MULTI:
3635                 case Tabular::APPEND_ROW:
3636                 case Tabular::APPEND_COLUMN:
3637                 case Tabular::DELETE_ROW:
3638                 case Tabular::DELETE_COLUMN:
3639                 case Tabular::COPY_ROW:
3640                 case Tabular::COPY_COLUMN:
3641                 case Tabular::SET_TOP_SPACE:
3642                 case Tabular::SET_BOTTOM_SPACE:
3643                 case Tabular::SET_INTERLINE_SPACE:
3644                         status.clear();
3645                         return true;
3646
3647                 case Tabular::MULTICOLUMN:
3648                         status.setEnabled(sel_row_start == sel_row_end);
3649                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3650                         break;
3651
3652                 case Tabular::SET_ALL_LINES:
3653                 case Tabular::UNSET_ALL_LINES:
3654                 case Tabular::SET_BORDER_LINES:
3655                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3656                         break;
3657
3658                 case Tabular::TOGGLE_LINE_TOP:
3659                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3660                         status.setOnOff(tabular.topLine(cur.idx()));
3661                         break;
3662
3663                 case Tabular::TOGGLE_LINE_BOTTOM:
3664                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3665                         status.setOnOff(tabular.bottomLine(cur.idx()));
3666                         break;
3667
3668                 case Tabular::TOGGLE_LINE_LEFT:
3669                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3670                         status.setOnOff(tabular.leftLine(cur.idx()));
3671                         break;
3672
3673                 case Tabular::TOGGLE_LINE_RIGHT:
3674                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3675                         status.setOnOff(tabular.rightLine(cur.idx()));
3676                         break;
3677
3678                 case Tabular::M_ALIGN_LEFT:
3679                         flag = false;
3680                 case Tabular::ALIGN_LEFT:
3681                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3682                         break;
3683
3684                 case Tabular::M_ALIGN_RIGHT:
3685                         flag = false;
3686                 case Tabular::ALIGN_RIGHT:
3687                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3688                         break;
3689
3690                 case Tabular::M_ALIGN_CENTER:
3691                         flag = false;
3692                 case Tabular::ALIGN_CENTER:
3693                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3694                         break;
3695
3696                 case Tabular::ALIGN_BLOCK:
3697                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3698                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3699                         break;
3700
3701                 case Tabular::M_VALIGN_TOP:
3702                         flag = false;
3703                 case Tabular::VALIGN_TOP:
3704                         status.setOnOff(
3705                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3706                         break;
3707
3708                 case Tabular::M_VALIGN_BOTTOM:
3709                         flag = false;
3710                 case Tabular::VALIGN_BOTTOM:
3711                         status.setOnOff(
3712                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3713                         break;
3714
3715                 case Tabular::M_VALIGN_MIDDLE:
3716                         flag = false;
3717                 case Tabular::VALIGN_MIDDLE:
3718                         status.setOnOff(
3719                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3720                         break;
3721
3722                 case Tabular::SET_LONGTABULAR:
3723                         status.setOnOff(tabular.is_long_tabular);
3724                         break;
3725
3726                 case Tabular::UNSET_LONGTABULAR:
3727                         status.setOnOff(!tabular.is_long_tabular);
3728                         break;
3729
3730                 case Tabular::TOGGLE_ROTATE_TABULAR:
3731                 case Tabular::SET_ROTATE_TABULAR:
3732                         status.setOnOff(tabular.rotate);
3733                         break;
3734
3735                 case Tabular::UNSET_ROTATE_TABULAR:
3736                         status.setOnOff(!tabular.rotate);
3737                         break;
3738
3739                 case Tabular::TOGGLE_ROTATE_CELL:
3740                 case Tabular::SET_ROTATE_CELL:
3741                         status.setOnOff(!oneCellHasRotationState(false,
3742                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3743                         break;
3744
3745                 case Tabular::UNSET_ROTATE_CELL:
3746                         status.setOnOff(!oneCellHasRotationState(true,
3747                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3748                         break;
3749
3750                 case Tabular::SET_USEBOX:
3751                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3752                         break;
3753
3754                 case Tabular::SET_LTFIRSTHEAD:
3755                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3756                         break;
3757
3758                 case Tabular::UNSET_LTFIRSTHEAD:
3759                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3760                         break;
3761
3762                 case Tabular::SET_LTHEAD:
3763                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3764                         break;
3765
3766                 case Tabular::UNSET_LTHEAD:
3767                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3768                         break;
3769
3770                 case Tabular::SET_LTFOOT:
3771                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3772                         break;
3773
3774                 case Tabular::UNSET_LTFOOT:
3775                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3776                         break;
3777
3778                 case Tabular::SET_LTLASTFOOT:
3779                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3780                         break;
3781
3782                 case Tabular::UNSET_LTLASTFOOT:
3783                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3784                         break;
3785
3786                 case Tabular::SET_LTNEWPAGE:
3787                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3788                         break;
3789
3790                 case Tabular::TOGGLE_LTCAPTION:
3791                         status.setEnabled(sel_row_start == sel_row_end);
3792                         status.setOnOff(tabular.ltCaption(sel_row_start));
3793                         break;
3794
3795                 case Tabular::SET_BOOKTABS:
3796                         status.setOnOff(tabular.use_booktabs);
3797                         break;
3798
3799                 case Tabular::UNSET_BOOKTABS:
3800                         status.setOnOff(!tabular.use_booktabs);
3801                         break;
3802
3803                 default:
3804                         status.clear();
3805                         status.setEnabled(false);
3806                         break;
3807                 }
3808                 return true;
3809         }
3810
3811         // These are only enabled inside tabular
3812         case LFUN_CELL_BACKWARD:
3813         case LFUN_CELL_FORWARD:
3814                 status.setEnabled(true);
3815                 return true;
3816
3817         // disable these with multiple cells selected
3818         case LFUN_INSET_INSERT:
3819         case LFUN_TABULAR_INSERT:
3820         case LFUN_FLEX_INSERT:
3821         case LFUN_FLOAT_INSERT:
3822         case LFUN_FLOAT_WIDE_INSERT:
3823         case LFUN_FOOTNOTE_INSERT:
3824         case LFUN_MARGINALNOTE_INSERT:
3825         case LFUN_MATH_INSERT:
3826         case LFUN_MATH_MODE:
3827         case LFUN_MATH_MUTATE:
3828         case LFUN_MATH_DISPLAY:
3829         case LFUN_NOTE_INSERT:
3830         case LFUN_OPTIONAL_INSERT:
3831         case LFUN_BOX_INSERT:
3832         case LFUN_BRANCH_INSERT:
3833         case LFUN_WRAP_INSERT:
3834         case LFUN_ERT_INSERT: {
3835                 if (cur.selIsMultiCell()) {
3836                         status.setEnabled(false);
3837                         return true;
3838                 } else
3839                         return cell(cur.idx())->getStatus(cur, cmd, status);
3840         }
3841
3842         // disable in non-fixed-width cells
3843         case LFUN_NEWLINE_INSERT:
3844         case LFUN_BREAK_PARAGRAPH: {
3845                 if (tabular.getPWidth(cur.idx()).zero()) {
3846                         status.setEnabled(false);
3847                         return true;
3848                 } else
3849                         return cell(cur.idx())->getStatus(cur, cmd, status);
3850         }
3851
3852         case LFUN_NEWPAGE_INSERT:
3853                 status.setEnabled(false);
3854                 return true;
3855
3856         case LFUN_PASTE:
3857                 if (cur.selIsMultiCell()) {
3858                         status.setEnabled(false);
3859                         status.message(_("You cannot paste into a multicell selection."));
3860                         return true;
3861                 }
3862                 if (tabularStackDirty() && theClipboard().isInternal()) {
3863                         status.setEnabled(true);
3864                         return true;
3865                 } 
3866                 return cell(cur.idx())->getStatus(cur, cmd, status);
3867
3868         case LFUN_INSET_MODIFY:
3869                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3870                         status.setEnabled(true);
3871                         return true;
3872                 }
3873                 // Fall through
3874
3875         default:
3876                 // we try to handle this event in the insets dispatch function.
3877                 return cell(cur.idx())->getStatus(cur, cmd, status);
3878         }
3879 }
3880
3881
3882 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
3883 {
3884         return tabular.latex(os, runparams);
3885 }
3886
3887
3888 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
3889 {
3890         os << '\n'; // output table on a new line
3891         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3892         tabular.plaintext(os, runparams, dp, false, 0);
3893         return PLAINTEXT_NEWLINE;
3894 }
3895
3896
3897 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
3898 {
3899         int ret = 0;
3900         Inset * master = 0;
3901
3902         // FIXME: Why not pass a proper DocIterator here?
3903 #if 0
3904         // if the table is inside a float it doesn't need the informaltable
3905         // wrapper. Search for it.
3906         for (master = owner(); master; master = master->owner())
3907                 if (master->lyxCode() == FLOAT_CODE)
3908                         break;
3909 #endif
3910
3911         if (!master) {
3912                 os << "<informaltable>";
3913                 ++ret;
3914         }
3915         ret += tabular.docbook(os, runparams);
3916         if (!master) {
3917                 os << "</informaltable>";
3918                 ++ret;
3919         }
3920         return ret;
3921 }
3922
3923
3924 void InsetTabular::validate(LaTeXFeatures & features) const
3925 {
3926         tabular.validate(features);
3927 }
3928
3929
3930 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
3931 {
3932         return tabular.cellInset(idx);
3933 }
3934
3935
3936 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
3937 {
3938         return tabular.cellInset(idx);
3939 }
3940
3941
3942 void InsetTabular::cursorPos(BufferView const & bv,
3943                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3944 {
3945         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3946
3947         // y offset     correction
3948         int const row = tabular.cellRow(sl.idx());
3949         for (int i = 0; i <= row; ++i) {
3950                 if (i != 0) {
3951                         y += tabular.rowAscent(i);
3952                         y += tabular.getAdditionalHeight(i);
3953                 }
3954                 if (i != row)
3955                         y += tabular.rowDescent(i);
3956         }
3957
3958         // x offset correction
3959         int const col = tabular.cellColumn(sl.idx());
3960         int idx = tabular.cellIndex(row, 0);
3961         for (int j = 0; j < col; ++j) {
3962                 if (tabular.isPartOfMultiColumn(row, j))
3963                         continue;
3964                 x += tabular.columnWidth(idx);
3965                 ++idx;
3966         }
3967         x += tabular.getBeginningOfTextInCell(idx);
3968         x += ADD_TO_TABULAR_WIDTH;
3969         x += scx_;
3970 }
3971
3972
3973 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3974 {
3975         int xx = 0;
3976         int yy = 0;
3977         Inset const & inset = *tabular.cellInset(cell);
3978         Point o = bv.coordCache().getInsets().xy(&inset);
3979         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3980         int const xend = xbeg + tabular.columnWidth(cell);
3981         row_type const row = tabular.cellRow(cell);
3982         int const ybeg = o.y_ - tabular.rowAscent(row) -
3983                          tabular.getAdditionalHeight(row);
3984         int const yend = o.y_ + tabular.rowDescent(row);
3985
3986         if (x < xbeg)
3987                 xx = xbeg - x;
3988         else if (x > xend)
3989                 xx = x - xend;
3990
3991         if (y < ybeg)
3992                 yy = ybeg - y;
3993         else if (y > yend)
3994                 yy = y - yend;
3995
3996         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3997         //       << " ybeg=" << ybeg << " yend=" << yend
3998         //       << " xx=" << xx << " yy=" << yy
3999         //       << " dist=" << xx + yy << endl;
4000         return xx + yy;
4001 }
4002
4003
4004 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4005 {
4006         //lyxerr << "InsetTabular::editXY: " << this << endl;
4007         cur.selection() = false;
4008         cur.push(*this);
4009         cur.idx() = getNearestCell(cur.bv(), x, y);
4010         resetPos(cur);
4011         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4012 }
4013
4014
4015 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4016 {
4017         cur.idx() = getNearestCell(cur.bv(), x, y);
4018         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4019 }
4020
4021
4022 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4023 {
4024         idx_type idx_min = 0;
4025         int dist_min = numeric_limits<int>::max();
4026         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4027                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4028                         int const d = dist(bv, i, x, y);
4029                         if (d < dist_min) {
4030                                 dist_min = d;
4031                                 idx_min = i;
4032                         }
4033                 }
4034         }
4035         return idx_min;
4036 }
4037
4038
4039 int InsetTabular::cellXPos(idx_type const cell) const
4040 {
4041         idx_type c = cell;
4042
4043         for (; !tabular.isFirstCellInRow(c); --c)
4044                 ;
4045         int lx = 0;
4046         for (; c < cell; ++c)
4047                 lx += tabular.columnWidth(c);
4048
4049         return lx;
4050 }
4051
4052
4053 void InsetTabular::resetPos(Cursor & cur) const
4054 {
4055         BufferView & bv = cur.bv();
4056         int const maxwidth = bv.workWidth();
4057
4058         int const scx_old = scx_;
4059         int const i = cur.find(this);
4060         if (i == -1) {
4061                 scx_ = 0;
4062         } else {
4063                 int const X1 = 0;
4064                 int const X2 = maxwidth;
4065                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4066                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4067                 int const x2 = x1 + tabular.columnWidth(cur[i].idx());
4068
4069                 if (x1 < X1)
4070                         scx_ = X1 + 20 - x1;
4071                 else if (x2 > X2)
4072                         scx_ = X2 - 20 - x2;
4073                 else
4074                         scx_ = 0;
4075         }
4076
4077         // only update if offset changed
4078         if (scx_ != scx_old)
4079                 cur.updateFlags(Update::Force | Update::FitCursor);
4080 }
4081
4082
4083 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4084 {
4085         if (isRightToLeft(cur)) {
4086                 if (tabular.isFirstCellInRow(cur.idx())) {
4087                         row_type const row = tabular.cellRow(cur.idx());
4088                         if (row == tabular.row_info.size() - 1)
4089                                 return;
4090                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4091                 } else {
4092                         if (cur.idx() == 0)
4093                                 return;
4094                         --cur.idx();
4095                 }
4096         } else {
4097                 if (tabular.isLastCell(cur.idx()))
4098                         return;
4099                 ++cur.idx();
4100         }
4101         cur.pit() = 0;
4102         cur.pos() = 0;
4103         cur.boundary(false);
4104
4105         // in visual mode, place cursor at extreme left or right
4106         
4107         switch(entry_from) {
4108
4109         case ENTRY_DIRECTION_RIGHT:
4110                 cur.posVisToRowExtremity(false /* !left */);
4111                 break;
4112         case ENTRY_DIRECTION_LEFT:
4113                 cur.posVisToRowExtremity(true /* left */);
4114                 break;
4115         case ENTRY_DIRECTION_IGNORE:
4116                 // nothing to do in this case
4117                 break;
4118
4119         }
4120
4121         resetPos(cur);
4122 }
4123
4124
4125 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4126 {
4127         if (isRightToLeft(cur)) {
4128                 if (tabular.isLastCellInRow(cur.idx())) {
4129                         row_type const row = tabular.cellRow(cur.idx());
4130                         if (row == 0)
4131                                 return;
4132                         cur.idx() = tabular.getFirstCellInRow(row);
4133                         cur.idx() = tabular.cellAbove(cur.idx());
4134                 } else {
4135                         if (tabular.isLastCell(cur.idx()))
4136                                 return;
4137                         ++cur.idx();
4138                 }
4139         } else {
4140                 if (cur.idx() == 0) // first cell
4141                         return;
4142                 --cur.idx();
4143         }
4144         cur.pit() = cur.lastpit();
4145         cur.pos() = cur.lastpos();
4146
4147         // in visual mode, place cursor at extreme left or right
4148         
4149         switch(entry_from) {
4150
4151         case ENTRY_DIRECTION_RIGHT:
4152                 cur.posVisToRowExtremity(false /* !left */);
4153                 break;
4154         case ENTRY_DIRECTION_LEFT:
4155                 cur.posVisToRowExtremity(true /* left */);
4156                 break;
4157         case ENTRY_DIRECTION_IGNORE:
4158                 // nothing to do in this case
4159                 break;
4160
4161         }
4162
4163         resetPos(cur);
4164 }
4165
4166
4167 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4168 {
4169         Tabular::Feature action = Tabular::LAST_ACTION;
4170
4171         int i = 0;
4172         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4173                 string const tmp = tabularFeature[i].feature;
4174
4175                 if (tmp == what.substr(0, tmp.length())) {
4176                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4177                         //tabularFeatures[i].feature.length()))
4178                         action = tabularFeature[i].action;
4179                         break;
4180                 }
4181         }
4182         if (action == Tabular::LAST_ACTION)
4183                 return false;
4184
4185         string const val =
4186                 ltrim(what.substr(tabularFeature[i].feature.length()));
4187         tabularFeatures(cur, action, val);
4188         return true;
4189 }
4190
4191
4192 static void checkLongtableSpecial(Tabular::ltType & ltt,
4193                           string const & special, bool & flag)
4194 {
4195         if (special == "dl_above") {
4196                 ltt.topDL = flag;
4197                 ltt.set = false;
4198         } else if (special == "dl_below") {
4199                 ltt.bottomDL = flag;
4200                 ltt.set = false;
4201         } else if (special == "empty") {
4202                 ltt.empty = flag;
4203                 ltt.set = false;
4204         } else if (flag) {
4205                 ltt.empty = false;
4206                 ltt.set = true;
4207         }
4208 }
4209
4210 bool InsetTabular::oneCellHasRotationState(bool rotated,
4211                 row_type row_start, row_type row_end,
4212                 col_type col_start, col_type col_end) const {
4213
4214         for (row_type i = row_start; i <= row_end; ++i) {
4215                 for (col_type j = col_start; j <= col_end; ++j) {
4216                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4217                                 == rotated) {
4218                                 return true;
4219                         }
4220                 }
4221         }
4222         return false;
4223 }
4224
4225 void InsetTabular::tabularFeatures(Cursor & cur,
4226         Tabular::Feature feature, string const & value)
4227 {
4228         col_type sel_col_start;
4229         col_type sel_col_end;
4230         row_type sel_row_start;
4231         row_type sel_row_end;
4232         bool setLines = false;
4233         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4234         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4235
4236         switch (feature) {
4237
4238         case Tabular::M_ALIGN_LEFT:
4239         case Tabular::ALIGN_LEFT:
4240                 setAlign = LYX_ALIGN_LEFT;
4241                 break;
4242
4243         case Tabular::M_ALIGN_RIGHT:
4244         case Tabular::ALIGN_RIGHT:
4245                 setAlign = LYX_ALIGN_RIGHT;
4246                 break;
4247
4248         case Tabular::M_ALIGN_CENTER:
4249         case Tabular::ALIGN_CENTER:
4250                 setAlign = LYX_ALIGN_CENTER;
4251                 break;
4252
4253         case Tabular::ALIGN_BLOCK:
4254                 setAlign = LYX_ALIGN_BLOCK;
4255                 break;
4256
4257         case Tabular::M_VALIGN_TOP:
4258         case Tabular::VALIGN_TOP:
4259                 setVAlign = Tabular::LYX_VALIGN_TOP;
4260                 break;
4261
4262         case Tabular::M_VALIGN_BOTTOM:
4263         case Tabular::VALIGN_BOTTOM:
4264                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4265                 break;
4266
4267         case Tabular::M_VALIGN_MIDDLE:
4268         case Tabular::VALIGN_MIDDLE:
4269                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4270                 break;
4271
4272         default:
4273                 break;
4274         }
4275
4276         cur.recordUndoInset(ATOMIC_UNDO);
4277
4278         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4279         row_type const row = tabular.cellRow(cur.idx());
4280         col_type const column = tabular.cellColumn(cur.idx());
4281         bool flag = true;
4282         Tabular::ltType ltt;
4283
4284         switch (feature) {
4285
4286         case Tabular::SET_PWIDTH: {
4287                 Length const len(value);
4288                 tabular.setColumnPWidth(cur, cur.idx(), len);
4289                 if (len.zero()
4290                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4291                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4292                 break;
4293         }
4294
4295         case Tabular::SET_MPWIDTH:
4296                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4297                 break;
4298
4299         case Tabular::SET_SPECIAL_COLUMN:
4300         case Tabular::SET_SPECIAL_MULTI:
4301                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4302                 break;
4303
4304         case Tabular::APPEND_ROW:
4305                 // append the row into the tabular
4306                 tabular.appendRow(cur.idx());
4307                 break;
4308
4309         case Tabular::APPEND_COLUMN:
4310                 // append the column into the tabular
4311                 tabular.appendColumn(cur.idx());
4312                 cur.idx() = tabular.cellIndex(row, column);
4313                 break;
4314
4315         case Tabular::DELETE_ROW:
4316                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4317                         tabular.deleteRow(sel_row_start);
4318                 if (sel_row_start >= tabular.row_info.size())
4319                         --sel_row_start;
4320                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4321                 cur.pit() = 0;
4322                 cur.pos() = 0;
4323                 cur.selection() = false;
4324                 break;
4325
4326         case Tabular::DELETE_COLUMN:
4327                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4328                         tabular.deleteColumn(sel_col_start);
4329                 if (sel_col_start >= tabular.column_info.size())
4330                         --sel_col_start;
4331                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4332                 cur.pit() = 0;
4333                 cur.pos() = 0;
4334                 cur.selection() = false;
4335                 break;
4336
4337         case Tabular::COPY_ROW:
4338                 tabular.copyRow(row);
4339                 break;
4340
4341         case Tabular::COPY_COLUMN:
4342                 tabular.copyColumn(column);
4343                 cur.idx() = tabular.cellIndex(row, column);
4344                 break;
4345
4346         case Tabular::TOGGLE_LINE_TOP: {
4347                 bool lineSet = !tabular.topLine(cur.idx());
4348                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4349                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4350                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4351                 break;
4352         }
4353
4354         case Tabular::TOGGLE_LINE_BOTTOM: {
4355                 bool lineSet = !tabular.bottomLine(cur.idx());
4356                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4357                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4358                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4359                 break;
4360         }
4361
4362         case Tabular::TOGGLE_LINE_LEFT: {
4363                 bool lineSet = !tabular.leftLine(cur.idx());
4364                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4365                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4366                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4367                 break;
4368         }
4369
4370         case Tabular::TOGGLE_LINE_RIGHT: {
4371                 bool lineSet = !tabular.rightLine(cur.idx());
4372                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4373                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4374                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4375                 break;
4376         }
4377
4378         case Tabular::M_ALIGN_LEFT:
4379         case Tabular::M_ALIGN_RIGHT:
4380         case Tabular::M_ALIGN_CENTER:
4381                 flag = false;
4382         case Tabular::ALIGN_LEFT:
4383         case Tabular::ALIGN_RIGHT:
4384         case Tabular::ALIGN_CENTER:
4385         case Tabular::ALIGN_BLOCK:
4386                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4387                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4388                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4389                 break;
4390
4391         case Tabular::M_VALIGN_TOP:
4392         case Tabular::M_VALIGN_BOTTOM:
4393         case Tabular::M_VALIGN_MIDDLE:
4394                 flag = false;
4395         case Tabular::VALIGN_TOP:
4396         case Tabular::VALIGN_BOTTOM:
4397         case Tabular::VALIGN_MIDDLE:
4398                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4399                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4400                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4401                 break;
4402
4403         case Tabular::MULTICOLUMN: {
4404                 if (!cur.selection()) {
4405                         // just multicol for one single cell
4406                         // check whether we are completely in a multicol
4407                         if (tabular.isMultiColumn(cur.idx()))
4408                                 tabular.unsetMultiColumn(cur.idx());
4409                         else
4410                                 tabular.setMultiColumn(cur.idx(), 1);
4411                         break;
4412                 }
4413                 // we have a selection so this means we just add all this
4414                 // cells to form a multicolumn cell
4415                 idx_type const s_start = cur.selBegin().idx();
4416                 idx_type const s_end = cur.selEnd().idx();
4417                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4418                 cur.idx() = s_start;
4419                 cur.pit() = 0;
4420                 cur.pos() = 0;
4421                 cur.selection() = false;
4422                 break;
4423         }
4424
4425         case Tabular::SET_ALL_LINES:
4426                 setLines = true;
4427         case Tabular::UNSET_ALL_LINES:
4428                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4429                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4430                                 tabular.setAllLines(
4431                                         tabular.cellIndex(i,j), setLines);
4432                 break;
4433
4434         case Tabular::SET_BORDER_LINES:
4435                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4436                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4437                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4438                 }
4439                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4440                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4441                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4442                 }
4443                 break;
4444
4445         case Tabular::SET_LONGTABULAR:
4446                 tabular.is_long_tabular = true;
4447                 break;
4448
4449         case Tabular::UNSET_LONGTABULAR:
4450                 tabular.is_long_tabular = false;
4451                 break;
4452
4453         case Tabular::SET_ROTATE_TABULAR:
4454                 tabular.rotate = true;
4455                 break;
4456
4457         case Tabular::UNSET_ROTATE_TABULAR:
4458                 tabular.rotate = false;
4459                 break;
4460
4461         case Tabular::TOGGLE_ROTATE_TABULAR:
4462                 tabular.rotate = !tabular.rotate;
4463                 break;
4464
4465         case Tabular::SET_ROTATE_CELL:
4466                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4467                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4468                                 tabular.setRotateCell(
4469                                         tabular.cellIndex(i, j), true);
4470                 break;
4471
4472         case Tabular::UNSET_ROTATE_CELL:
4473                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4474                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4475                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4476                 break;
4477
4478         case Tabular::TOGGLE_ROTATE_CELL:
4479                 {
4480                 bool oneNotRotated = oneCellHasRotationState(false,
4481                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4482
4483                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4484                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4485                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4486                                                                           oneNotRotated);
4487                 }
4488                 break;
4489
4490         case Tabular::SET_USEBOX: {
4491                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4492                 if (val == tabular.getUsebox(cur.idx()))
4493                         val = Tabular::BOX_NONE;
4494                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4495                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4496                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4497                 break;
4498         }
4499
4500         case Tabular::UNSET_LTFIRSTHEAD:
4501                 flag = false;
4502         case Tabular::SET_LTFIRSTHEAD:
4503                 tabular.getRowOfLTFirstHead(row, ltt);
4504                 checkLongtableSpecial(ltt, value, flag);
4505                 tabular.setLTHead(row, flag, ltt, true);
4506                 break;
4507
4508         case Tabular::UNSET_LTHEAD:
4509                 flag = false;
4510         case Tabular::SET_LTHEAD:
4511                 tabular.getRowOfLTHead(row, ltt);
4512                 checkLongtableSpecial(ltt, value, flag);
4513                 tabular.setLTHead(row, flag, ltt, false);
4514                 break;
4515
4516         case Tabular::UNSET_LTFOOT:
4517                 flag = false;
4518         case Tabular::SET_LTFOOT:
4519                 tabular.getRowOfLTFoot(row, ltt);
4520                 checkLongtableSpecial(ltt, value, flag);
4521                 tabular.setLTFoot(row, flag, ltt, false);
4522                 break;
4523
4524         case Tabular::UNSET_LTLASTFOOT:
4525                 flag = false;
4526         case Tabular::SET_LTLASTFOOT:
4527                 tabular.getRowOfLTLastFoot(row, ltt);
4528                 checkLongtableSpecial(ltt, value, flag);
4529                 tabular.setLTFoot(row, flag, ltt, true);
4530                 break;
4531
4532         case Tabular::SET_LTNEWPAGE:
4533                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4534                 break;
4535
4536         case Tabular::TOGGLE_LTCAPTION:
4537                 cur.idx() = tabular.setLTCaption(row, !tabular.ltCaption(row));
4538                 cur.pit() = 0;
4539                 cur.pos() = 0;
4540                 cur.selection() = false;
4541                 break;
4542
4543         case Tabular::SET_BOOKTABS:
4544                 tabular.use_booktabs = true;
4545                 break;
4546
4547         case Tabular::UNSET_BOOKTABS:
4548                 tabular.use_booktabs = false;
4549                 break;
4550
4551         case Tabular::SET_TOP_SPACE: {
4552                 Length len;
4553                 if (value == "default")
4554                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4555                                 tabular.row_info[i].top_space_default = true;
4556                 else if (isValidLength(value, &len))
4557                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4558                                 tabular.row_info[i].top_space_default = false;
4559                                 tabular.row_info[i].top_space = len;
4560                         }
4561                 else
4562                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4563                                 tabular.row_info[i].top_space_default = false;
4564                                 tabular.row_info[i].top_space = len;
4565                         }
4566                 break;
4567         }
4568
4569         case Tabular::SET_BOTTOM_SPACE: {
4570                 Length len;
4571                 if (value == "default")
4572                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4573                                 tabular.row_info[i].bottom_space_default = true;
4574                 else if (isValidLength(value, &len))
4575                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4576                                 tabular.row_info[i].bottom_space_default = false;
4577                                 tabular.row_info[i].bottom_space = len;
4578                         }
4579                 else
4580                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4581                                 tabular.row_info[i].bottom_space_default = false;
4582                                 tabular.row_info[i].bottom_space = len;
4583                         }
4584                 break;
4585         }
4586
4587         case Tabular::SET_INTERLINE_SPACE: {
4588                 Length len;
4589                 if (value == "default")
4590                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4591                                 tabular.row_info[i].interline_space_default = true;
4592                 else if (isValidLength(value, &len))
4593                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4594                                 tabular.row_info[i].interline_space_default = false;
4595                                 tabular.row_info[i].interline_space = len;
4596                         }
4597                 else
4598                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4599                                 tabular.row_info[i].interline_space_default = false;
4600                                 tabular.row_info[i].interline_space = len;
4601                         }
4602                 break;
4603         }
4604
4605         // dummy stuff just to avoid warnings
4606         case Tabular::LAST_ACTION:
4607                 break;
4608         }
4609 }
4610
4611
4612 bool InsetTabular::showInsetDialog(BufferView * bv) const
4613 {
4614         bv->showDialog("tabular", params2string(*this),
4615                 const_cast<InsetTabular *>(this));
4616         return true;
4617 }
4618
4619
4620 void InsetTabular::openLayoutDialog(BufferView * bv) const
4621 {
4622         bv->showDialog("tabular", params2string(*this),
4623                 const_cast<InsetTabular *>(this));
4624 }
4625
4626
4627 bool InsetTabular::copySelection(Cursor & cur)
4628 {
4629         if (!cur.selection())
4630                 return false;
4631
4632         row_type rs, re;
4633         col_type cs, ce;
4634         getSelection(cur, rs, re, cs, ce);
4635
4636         paste_tabular.reset(new Tabular(tabular));
4637
4638         for (row_type i = 0; i < rs; ++i)
4639                 paste_tabular->deleteRow(0);
4640
4641         row_type const rows = re - rs + 1;
4642         while (paste_tabular->row_info.size() > rows)
4643                 paste_tabular->deleteRow(rows);
4644
4645         for (col_type i = 0; i < cs; ++i)
4646                 paste_tabular->deleteColumn(0);
4647
4648         col_type const columns = ce - cs + 1;
4649         while (paste_tabular->column_info.size() > columns)
4650                 paste_tabular->deleteColumn(columns);
4651
4652         paste_tabular->setBuffer(tabular.buffer());
4653
4654         odocstringstream os;
4655         OutputParams const runparams(0);
4656         paste_tabular->plaintext(os, runparams, 0, true, '\t');
4657         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4658         cap::copySelection(cur, os.str());
4659
4660         // mark tabular stack dirty
4661         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4662         // when we (hopefully) have a one-for-all paste mechanism.
4663         // This must be called after cap::copySelection.
4664         dirtyTabularStack(true);
4665
4666         return true;
4667 }
4668
4669
4670 bool InsetTabular::pasteClipboard(Cursor & cur)
4671 {
4672         if (!paste_tabular)
4673                 return false;
4674         col_type const actcol = tabular.cellColumn(cur.idx());
4675         row_type const actrow = tabular.cellRow(cur.idx());
4676         for (row_type r1 = 0, r2 = actrow;
4677              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
4678              ++r1, ++r2) {
4679                 for (col_type c1 = 0, c2 = actcol;
4680                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
4681                     ++c1, ++c2) {
4682                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4683                             tabular.isPartOfMultiColumn(r2, c2))
4684                                 continue;
4685                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4686                                 --c2;
4687                                 continue;
4688                         }
4689                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4690                                 --c1;
4691                                 continue;
4692                         }
4693                         shared_ptr<InsetTableCell> inset(
4694                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
4695                         tabular.setCellInset(r2, c2, inset);
4696                         // FIXME: change tracking (MG)
4697                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4698                                                 Change::INSERTED : Change::UNCHANGED));
4699                         cur.pos() = 0;
4700                 }
4701         }
4702         return true;
4703 }
4704
4705
4706 void InsetTabular::cutSelection(Cursor & cur)
4707 {
4708         if (!cur.selection())
4709                 return;
4710
4711         row_type rs, re;
4712         col_type cs, ce;
4713         getSelection(cur, rs, re, cs, ce);
4714         for (row_type i = rs; i <= re; ++i) {
4715                 for (col_type j = cs; j <= ce; ++j) {
4716                         shared_ptr<InsetTableCell> t
4717                                 = cell(tabular.cellIndex(i, j));
4718                         if (cur.buffer().params().trackChanges)
4719                                 // FIXME: Change tracking (MG)
4720                                 t->setChange(Change(Change::DELETED));
4721                         else
4722                                 t->clear();
4723                 }
4724         }
4725
4726         // cursor position might be invalid now
4727         if (cur.pit() > cur.lastpit())
4728                 cur.pit() = cur.lastpit();
4729         if (cur.pos() > cur.lastpos())
4730                 cur.pos() = cur.lastpos();
4731         cur.clearSelection();
4732 }
4733
4734
4735 bool InsetTabular::isRightToLeft(Cursor & cur) const
4736 {
4737         LASSERT(cur.depth() > 1, /**/);
4738         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4739         pos_type const parentpos = cur[cur.depth() - 2].pos();
4740         return parentpar.getFontSettings(cur.bv().buffer().params(),
4741                                          parentpos).language()->rightToLeft();
4742 }
4743
4744 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
4745                                  bool intoInsets)
4746 {
4747         LASSERT(stidx <= enidx, return docstring());
4748         docstring retval;
4749         col_type const col1 = tabular.cellColumn(stidx);
4750         col_type const col2 = tabular.cellColumn(enidx);
4751         row_type const row1 = tabular.cellRow(stidx);
4752         row_type const row2 = tabular.cellRow(enidx);
4753         bool first = true;
4754         for (col_type col = col1; col <= col2; col++)
4755                 for (row_type row = row1; row <= row2; row++) {
4756                         if (!first)
4757                                 retval += "\n";
4758                         else
4759                                 first = false;
4760                         retval += tabular.cellInset(row, col)->asString(intoInsets);
4761                 }
4762         return retval;
4763 }
4764
4765
4766 void InsetTabular::getSelection(Cursor & cur,
4767         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4768 {
4769         CursorSlice const & beg = cur.selBegin();
4770         CursorSlice const & end = cur.selEnd();
4771         cs = tabular.cellColumn(beg.idx());
4772         ce = tabular.cellColumn(end.idx());
4773         if (cs > ce) {
4774                 ce = cs;
4775                 cs = tabular.cellColumn(end.idx());
4776         } else {
4777                 ce = tabular.cellRightColumn(end.idx());
4778         }
4779
4780         rs = tabular.cellRow(beg.idx());
4781         re = tabular.cellRow(end.idx());
4782         if (rs > re)
4783                 swap(rs, re);
4784 }
4785
4786
4787 Text * InsetTabular::getText(int idx) const
4788 {
4789         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4790 }
4791
4792
4793 void InsetTabular::setChange(Change const & change)
4794 {
4795         for (idx_type idx = 0; idx < nargs(); ++idx)
4796                 cell(idx)->setChange(change);
4797 }
4798
4799
4800 void InsetTabular::acceptChanges(BufferParams const & bparams)
4801 {
4802         for (idx_type idx = 0; idx < nargs(); ++idx)
4803                 cell(idx)->acceptChanges(bparams);
4804 }
4805
4806
4807 void InsetTabular::rejectChanges(BufferParams const & bparams)
4808 {
4809         for (idx_type idx = 0; idx < nargs(); ++idx)
4810                 cell(idx)->rejectChanges(bparams);
4811 }
4812
4813
4814 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4815 {
4816         return tabular.getPWidth(cell).zero();
4817 }
4818
4819
4820 bool InsetTabular::forcePlainLayout(idx_type cell) const
4821 {
4822         return !tabular.getPWidth(cell).zero();
4823 }
4824
4825
4826 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4827                                      bool usePaste)
4828 {
4829         if (buf.length() <= 0)
4830                 return true;
4831
4832         col_type cols = 1;
4833         row_type rows = 1;
4834         col_type maxCols = 1;
4835         size_t const len = buf.length();
4836         size_t p = 0;
4837
4838         while (p < len &&
4839                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4840                 switch (buf[p]) {
4841                 case '\t':
4842                         ++cols;
4843                         break;
4844                 case '\n':
4845                         if (p + 1 < len)
4846                                 ++rows;
4847                         maxCols = max(cols, maxCols);
4848                         cols = 1;
4849                         break;
4850                 }
4851                 ++p;
4852         }
4853         maxCols = max(cols, maxCols);
4854         Tabular * loctab;
4855         idx_type cell = 0;
4856         col_type ocol = 0;
4857         row_type row = 0;
4858         if (usePaste) {
4859                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
4860                 loctab = paste_tabular.get();
4861                 cols = 0;
4862                 dirtyTabularStack(true);
4863         } else {
4864                 loctab = &tabular;
4865                 cell = bv.cursor().idx();
4866                 ocol = tabular.cellColumn(cell);
4867                 row = tabular.cellRow(cell);
4868         }
4869
4870         size_t op = 0;
4871         idx_type const cells = loctab->numberofcells;
4872         p = 0;
4873         cols = ocol;
4874         rows = loctab->row_info.size();
4875         col_type const columns = loctab->column_info.size();
4876
4877         while (cell < cells && p < len && row < rows &&
4878                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4879         {
4880                 if (p >= len)
4881                         break;
4882                 switch (buf[p]) {
4883                 case '\t':
4884                         // we can only set this if we are not too far right
4885                         if (cols < columns) {
4886                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4887                                 Font const font = bv.textMetrics(&inset->text()).
4888                                         displayFont(0, 0);
4889                                 inset->setText(buf.substr(op, p - op), font,
4890                                                buffer().params().trackChanges);
4891                                 ++cols;
4892                                 ++cell;
4893                         }
4894                         break;
4895                 case '\n':
4896                         // we can only set this if we are not too far right
4897                         if (cols < columns) {
4898                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
4899                                 Font const font = bv.textMetrics(&inset->text()).
4900                                         displayFont(0, 0);
4901                                 inset->setText(buf.substr(op, p - op), font,
4902                                                buffer().params().trackChanges);
4903                         }
4904                         cols = ocol;
4905                         ++row;
4906                         if (row < rows)
4907                                 cell = loctab->cellIndex(row, cols);
4908                         break;
4909                 }
4910                 ++p;
4911                 op = p;
4912         }
4913         // check for the last cell if there is no trailing '\n'
4914         if (cell < cells && op < len) {
4915                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4916                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
4917                 inset->setText(buf.substr(op, len - op), font,
4918                         buffer().params().trackChanges);
4919         }
4920         return true;
4921 }
4922
4923
4924 void InsetTabular::addPreview(PreviewLoader & loader) const
4925 {
4926         row_type const rows = tabular.row_info.size();
4927         col_type const columns = tabular.column_info.size();
4928         for (row_type i = 0; i < rows; ++i) {
4929                 for (col_type j = 0; j < columns; ++j)
4930                         tabular.cellInset(i, j)->addPreview(loader);
4931         }
4932 }
4933
4934
4935 bool InsetTabular::completionSupported(Cursor const & cur) const
4936 {
4937         Cursor const & bvCur = cur.bv().cursor();
4938         if (&bvCur.inset() != this)
4939                 return false;
4940         return cur.text()->completionSupported(cur);
4941 }
4942
4943
4944 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
4945 {
4946         return completionSupported(cur);
4947 }
4948
4949
4950 bool InsetTabular::automaticInlineCompletion() const
4951 {
4952         return lyxrc.completion_inline_text;
4953 }
4954
4955
4956 bool InsetTabular::automaticPopupCompletion() const
4957 {
4958         return lyxrc.completion_popup_text;
4959 }
4960
4961
4962 bool InsetTabular::showCompletionCursor() const
4963 {
4964         return lyxrc.completion_cursor_text;
4965 }
4966
4967
4968 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
4969 {
4970         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
4971 }
4972
4973
4974 docstring InsetTabular::completionPrefix(Cursor const & cur) const
4975 {
4976         if (!completionSupported(cur))
4977                 return docstring();
4978         return cur.text()->completionPrefix(cur);
4979 }
4980
4981
4982 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
4983 {
4984         if (!completionSupported(cur))
4985                 return false;
4986
4987         return cur.text()->insertCompletion(cur, s, finished);
4988 }
4989
4990
4991 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
4992                                     Dimension & dim) const
4993 {
4994         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
4995         tm.completionPosAndDim(cur, x, y, dim);
4996 }
4997
4998
4999 void InsetTabular::string2params(string const & in, InsetTabular & inset)
5000 {
5001         istringstream data(in);
5002         Lexer lex;
5003         lex.setStream(data);
5004
5005         if (in.empty())
5006                 return;
5007
5008         string token;
5009         lex >> token;
5010         if (!lex || token != "tabular") {
5011                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
5012                 return;
5013         }
5014
5015         // This is part of the inset proper that is usually swallowed
5016         // by Buffer::readInset
5017         lex >> token;
5018         if (!lex || token != "Tabular") {
5019                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
5020                 return;
5021         }
5022
5023         inset.read(lex);
5024 }
5025
5026
5027 string InsetTabular::params2string(InsetTabular const & inset)
5028 {
5029         ostringstream data;
5030         data << "tabular" << ' ';
5031         inset.write(data);
5032         data << "\\end_inset\n";
5033         return data.str();
5034 }
5035
5036
5037 } // namespace lyx