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