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