]> git.lyx.org Git - features.git/blob - src/insets/insettext.C
rowlist2
[features.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13
14 #include "insettext.h"
15
16 #include "buffer.h"
17 #include "BufferView.h"
18 #include "CutAndPaste.h"
19 #include "debug.h"
20 #include "funcrequest.h"
21 #include "gettext.h"
22 #include "intl.h"
23 #include "LaTeXFeatures.h"
24 #include "LColor.h"
25 #include "lyxfont.h"
26 #include "lyxcursor.h"
27 #include "lyxfind.h"
28 #include "lyxlex.h"
29 #include "lyxrow.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "paragraph.h"
33 #include "ParagraphParameters.h"
34 #include "trans_mgr.h"
35 #include "undo_funcs.h"
36 #include "WordLangTuple.h"
37 #include "paragraph_funcs.h"
38 #include "sgml.h"
39 #include "rowpainter.h"
40 #include "insetnewline.h"
41
42 #include "frontends/Alert.h"
43 #include "frontends/Dialogs.h"
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46 #include "frontends/Painter.h"
47 #include "frontends/screen.h"
48
49 #include "support/textutils.h"
50 #include "support/LAssert.h"
51 #include "support/lstrings.h"
52 #include "support/lyxalgo.h" // lyx::count
53
54 #include <boost/bind.hpp>
55
56 #include <fstream>
57 #include <algorithm>
58 #include <cstdlib>
59 //#include <csignal>
60
61 using std::ostream;
62 using std::ifstream;
63 using std::endl;
64 using std::min;
65 using std::max;
66 using std::make_pair;
67 using std::vector;
68 using std::pair;
69 using std::for_each;
70
71 using lyx::pos_type;
72 using lyx::textclass_type;
73
74 // These functions should probably go into bufferview_funcs somehow (Jug)
75
76 void InsetText::saveLyXTextState(LyXText * t) const
77 {
78         // check if my paragraphs are still valid
79         ParagraphList::iterator it = paragraphs.begin();
80         ParagraphList::iterator end = paragraphs.end();
81         for (; it != end; ++it) {
82                 if (&*it == t->cursor.par())
83                         break;
84         }
85
86         if (it != end && t->cursor.pos() <= it->size()) {
87                 sstate.lpar = t->cursor.par();
88                 sstate.pos = t->cursor.pos();
89                 sstate.boundary = t->cursor.boundary();
90                 sstate.selstartpar = t->selection.start.par();
91                 sstate.selstartpos = t->selection.start.pos();
92                 sstate.selstartboundary = t->selection.start.boundary();
93                 sstate.selendpar = t->selection.end.par();
94                 sstate.selendpos = t->selection.end.pos();
95                 sstate.selendboundary = t->selection.end.boundary();
96                 sstate.selection = t->selection.set();
97                 sstate.mark_set = t->selection.mark();
98         } else {
99                 sstate.lpar = 0;
100         }
101 }
102
103
104 void InsetText::restoreLyXTextState(LyXText * t) const
105 {
106         if (!sstate.lpar)
107                 return;
108
109         t->selection.set(true);
110         /* at this point just to avoid the DEPM when setting the cursor */
111         t->selection.mark(sstate.mark_set);
112         if (sstate.selection) {
113                 t->setCursor(sstate.selstartpar, sstate.selstartpos,
114                              true, sstate.selstartboundary);
115                 t->selection.cursor = t->cursor;
116                 t->setCursor(sstate.selendpar, sstate.selendpos,
117                              true, sstate.selendboundary);
118                 t->setSelection();
119                 t->setCursor(sstate.lpar, sstate.pos);
120         } else {
121                 t->setCursor(sstate.lpar, sstate.pos, true, sstate.boundary);
122                 t->selection.cursor = t->cursor;
123                 t->selection.set(false);
124         }
125 }
126
127
128 InsetText::InnerCache::InnerCache(boost::shared_ptr<LyXText> t)
129 {
130         text = t;
131         remove = false;
132 }
133
134
135 InsetText::InsetText(BufferParams const & bp)
136         : UpdatableInset(), lt(0), in_update(false), do_resize(0),
137           do_reinit(false)
138 {
139         paragraphs.set(new Paragraph);
140         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
141         if (bp.tracking_changes)
142                 paragraphs.begin()->trackChanges();
143         init();
144 }
145
146
147 InsetText::InsetText(InsetText const & in, bool same_id)
148         : UpdatableInset(in, same_id), lt(0), in_update(false), do_resize(0),
149           do_reinit(false)
150 {
151         init(&in, same_id);
152 }
153
154
155 InsetText & InsetText::operator=(InsetText const & it)
156 {
157         init(&it);
158         return * this;
159 }
160
161
162 void InsetText::init(InsetText const * ins, bool same_id)
163 {
164         if (ins) {
165                 setParagraphData(&*(ins->paragraphs.begin()), same_id);
166                 autoBreakRows = ins->autoBreakRows;
167                 drawFrame_ = ins->drawFrame_;
168                 frame_color = ins->frame_color;
169                 if (same_id)
170                         id_ = ins->id_;
171         } else {
172                 for_each(paragraphs.begin(), paragraphs.end(),
173                          boost::bind(&Paragraph::setInsetOwner, _1, this));
174
175                 the_locking_inset = 0;
176                 drawFrame_ = NEVER;
177                 frame_color = LColor::insetframe;
178                 autoBreakRows = false;
179         }
180         top_y = 0;
181         insetAscent = 0;
182         insetDescent = 0;
183         insetWidth = 0;
184         old_max_width = 0;
185         no_selection = true;
186         need_update = FULL;
187         drawTextXOffset = 0;
188         drawTextYOffset = 0;
189         locked = false;
190         old_par = 0;
191         last_drawn_width = -1;
192         cached_bview = 0;
193         sstate.lpar = 0;
194         in_insetAllowed = false;
195 }
196
197
198 InsetText::~InsetText()
199 {
200         paragraphs.clear();
201 }
202
203
204 void InsetText::clear(bool just_mark_erased)
205 {
206         if (just_mark_erased) {
207                 ParagraphList::iterator it = paragraphs.begin();
208                 ParagraphList::iterator end = paragraphs.end();
209                 for (; it != end; ++it) {
210                         it->markErased();
211                 }
212                 need_update = FULL;
213                 return;
214         }
215
216         // This is a gross hack...
217         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
218
219         paragraphs.clear();
220         paragraphs.set(new Paragraph);
221         paragraphs.begin()->setInsetOwner(this);
222         paragraphs.begin()->layout(old_layout);
223
224         reinitLyXText();
225         need_update = INIT;
226 }
227
228
229 Inset * InsetText::clone(Buffer const &, bool same_id) const
230 {
231         return new InsetText(*this, same_id);
232 }
233
234
235 void InsetText::write(Buffer const * buf, ostream & os) const
236 {
237         os << "Text\n";
238         writeParagraphData(buf, os);
239 }
240
241
242 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
243 {
244         ParagraphList::iterator it = paragraphs.begin();
245         ParagraphList::iterator end = paragraphs.end();
246         Paragraph::depth_type dth = 0;
247         for (; it != end; ++it) {
248                 it->write(buf, os, buf->params, dth);
249         }
250 }
251
252
253 void InsetText::read(Buffer const * buf, LyXLex & lex)
254 {
255         string token;
256         Paragraph::depth_type depth = 0;
257
258         clear(false);
259
260         if (buf->params.tracking_changes)
261                 paragraphs.begin()->trackChanges();
262
263         // delete the initial paragraph
264         paragraphs.clear();
265         ParagraphList::iterator pit = paragraphs.begin();
266
267         while (lex.isOK()) {
268                 lex.nextToken();
269                 token = lex.getString();
270                 if (token.empty())
271                         continue;
272                 if (token == "\\end_inset") {
273                         break;
274                 }
275
276                 if (token == "\\the_end") {
277                         lex.printError("\\the_end read in inset! Error in document!");
278                         return;
279                 }
280
281                 // FIXME: ugly.
282                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
283         }
284
285         pit = paragraphs.begin();
286         ParagraphList::iterator const end = paragraphs.end();
287         for (; pit != end; ++pit)
288                 pit->setInsetOwner(this);
289
290         if (token != "\\end_inset") {
291                 lex.printError("Missing \\end_inset at this point. "
292                                            "Read: `$$Token'");
293         }
294         need_update = FULL;
295 }
296
297
298 int InsetText::ascent(BufferView * bv, LyXFont const &) const
299 {
300         insetAscent = getLyXText(bv)->rows().begin()->ascent_of_text() +
301                 TEXT_TO_INSET_OFFSET;
302         return insetAscent;
303 }
304
305
306 int InsetText::descent(BufferView * bv, LyXFont const &) const
307 {
308         LyXText * llt = getLyXText(bv);
309         insetDescent = llt->height - llt->rows().begin()->ascent_of_text() +
310                 TEXT_TO_INSET_OFFSET;
311         return insetDescent;
312 }
313
314
315 int InsetText::width(BufferView * bv, LyXFont const &) const
316 {
317         insetWidth = max(textWidth(bv), (int)getLyXText(bv)->width) +
318                 (2 * TEXT_TO_INSET_OFFSET);
319         insetWidth = max(insetWidth, 10);
320         return insetWidth;
321 }
322
323
324 int InsetText::textWidth(BufferView * bv, bool fordraw) const
325 {
326         int w;
327         if (!autoBreakRows) {
328                 w = -1;
329         } else {
330                 w = getMaxWidth(bv, this);
331         }
332         if (fordraw) {
333                 return max(w - (2 * TEXT_TO_INSET_OFFSET),
334                            (int)getLyXText(bv)->width);
335         } else if (w < 0) {
336             return -1;
337         }
338         return w - (2 * TEXT_TO_INSET_OFFSET);
339 }
340
341
342 void InsetText::draw(BufferView * bv, LyXFont const & f,
343                      int baseline, float & x) const
344 {
345         if (nodraw())
346                 return;
347
348         // update our idea of where we are. Clearly, we should
349         // not have to know this information.
350         if (top_x != int(x))
351                 top_x = int(x);
352
353         int const start_x = int(x);
354
355         Painter & pain = bv->painter();
356
357         // call these methods so that insetWidth, insetAscent and
358         // insetDescent have the right values.
359         width(bv, f);
360         ascent(bv, f);
361         descent(bv, f);
362
363         // repaint the background if needed
364         if (backgroundColor() != LColor::background)
365                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
366
367         // no draw is necessary !!!
368         if ((drawFrame_ == LOCKED) && !locked && paragraphs.begin()->empty()) {
369                 top_baseline = baseline;
370                 x += width(bv, f);
371                 need_update = NONE;
372                 return;
373         }
374
375         if (!owner())
376                 x += static_cast<float>(scroll());
377
378         top_baseline = baseline;
379         top_y = baseline - insetAscent;
380
381         if (last_drawn_width != insetWidth) {
382                 need_update |= FULL;
383                 last_drawn_width = insetWidth;
384         }
385
386         if (the_locking_inset && (cpar(bv) == inset_par)
387                 && (cpos(bv) == inset_pos)) {
388                 inset_x = cix(bv) - int(x) + drawTextXOffset;
389                 inset_y = ciy(bv) + drawTextYOffset;
390         }
391
392         bool clear = false;
393         if (!lt) {
394                 lt = getLyXText(bv);
395                 clear = true;
396         }
397         x += TEXT_TO_INSET_OFFSET;
398
399         RowList::iterator rowit = lt->rows().begin();
400         RowList::iterator end = lt->rows().end();
401
402         int y_offset = baseline - rowit->ascent_of_text();
403         int ph = pain.paperHeight();
404         int first = 0;
405         int y = y_offset;
406         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
407                 y += rowit->height();
408                 first += rowit->height();
409                 ++rowit;
410         }
411         if (y_offset < 0) {
412                 lt->top_y(-y_offset);
413                 first = y;
414                 y_offset = 0;
415         } else {
416                 lt->top_y(first);
417                 first = 0;
418         }
419
420         int yf = y_offset + first;
421         y = 0;
422         while ((rowit != end) && (yf < ph)) {
423                 RowPainter rp(*bv, *lt, *rowit);
424                 rp.paint(y + y_offset + first, int(x), y + lt->top_y());
425                 y += rowit->height();
426                 yf += rowit->height();
427                 ++rowit;
428         }
429
430         lt->clearPaint();
431
432         if ((drawFrame_ == ALWAYS) || (drawFrame_ == LOCKED && locked)) {
433                 drawFrame(pain, int(start_x));
434         }
435
436         x += insetWidth - TEXT_TO_INSET_OFFSET;
437
438         if (need_update != INIT) {
439                 need_update = NONE;
440         }
441         if (clear)
442                 lt = 0;
443 }
444
445
446 void InsetText::drawFrame(Painter & pain, int x) const
447 {
448         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
449         frame_x = x + ttoD2;
450         frame_y = top_baseline - insetAscent + ttoD2;
451         frame_w = insetWidth - TEXT_TO_INSET_OFFSET;
452         frame_h = insetAscent + insetDescent - TEXT_TO_INSET_OFFSET;
453         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
454                        frame_color);
455 }
456
457
458 void InsetText::update(BufferView * bv, bool reinit)
459 {
460         if (in_update) {
461                 if (reinit && owner()) {
462                         reinitLyXText();
463                         owner()->update(bv, true);
464                 }
465                 return;
466         }
467         in_update = true;
468
469         if (reinit || need_update == INIT) {
470                 need_update = FULL;
471                 // we should put this call where we set need_update to INIT!
472                 reinitLyXText();
473                 if (owner())
474                         owner()->update(bv, true);
475                 in_update = false;
476
477                 int nw = getMaxWidth(bv, this);
478                 if (nw > 0 && old_max_width != nw) {
479                         need_update |= INIT;
480                         old_max_width = nw;
481                 }
482                 return;
483         }
484
485         if (!autoBreakRows && paragraphs.begin()->next())
486                 collapseParagraphs(bv);
487
488         if (the_locking_inset) {
489                 inset_x = cix(bv) - top_x + drawTextXOffset;
490                 inset_y = ciy(bv) + drawTextYOffset;
491                 the_locking_inset->update(bv, reinit);
492         }
493
494         bool clear = false;
495         if (!lt) {
496                 lt = getLyXText(bv);
497                 clear = true;
498         }
499         if ((need_update & CURSOR_PAR) && (lt->refreshStatus() == LyXText::REFRESH_NONE) &&
500                 the_locking_inset) {
501                 lt->updateInset(the_locking_inset);
502         }
503
504         if (lt->refreshStatus() == LyXText::REFRESH_AREA)
505                 need_update |= FULL;
506         if (clear)
507                 lt = 0;
508
509         in_update = false;
510
511         int nw = getMaxWidth(bv, this);
512         if (nw > 0 && old_max_width != nw) {
513                 need_update |= INIT;
514                 old_max_width = nw;
515         }
516 }
517
518
519 void InsetText::setUpdateStatus(BufferView * bv, int what) const
520 {
521         // this does nothing dangerous so use only a localized buffer
522         LyXText * llt = getLyXText(bv);
523
524         need_update |= what;
525         // we have to redraw us full if our LyXText REFRESH_AREA or
526         // if we don't break row so that we only have one row to update!
527         if ((llt->refreshStatus() == LyXText::REFRESH_AREA) ||
528             (!autoBreakRows &&
529              (llt->refreshStatus() == LyXText::REFRESH_ROW)))
530         {
531                 need_update |= FULL;
532         } else if (llt->refreshStatus() == LyXText::REFRESH_ROW) {
533                 need_update |= CURSOR_PAR;
534         }
535
536         // this to not draw a selection when we redraw all of it!
537         if (need_update & CURSOR && !(need_update & SELECTION)) {
538                 if (llt->selection.set())
539                         need_update = FULL;
540                 llt->clearSelection();
541         }
542 }
543
544
545 void InsetText::updateLocal(BufferView * bv, int what, bool mark_dirty)
546 {
547         if (!autoBreakRows && paragraphs.begin()->next())
548                 collapseParagraphs(bv);
549         bool clear = false;
550         if (!lt) {
551                 lt = getLyXText(bv);
552                 clear = true;
553         }
554         lt->fullRebreak();
555         setUpdateStatus(bv, what);
556         bool flag = mark_dirty ||
557                 (((need_update != CURSOR) && (need_update != NONE)) ||
558                  (lt->refreshStatus() != LyXText::REFRESH_NONE) || lt->selection.set());
559         if (!lt->selection.set())
560                 lt->selection.cursor = lt->cursor;
561
562         bv->fitCursor();
563
564         if (flag) {
565                 lt->postPaint(0);
566                 bv->updateInset(const_cast<InsetText *>(this));
567         }
568
569         if (clear)
570                 lt = 0;
571
572         if (need_update == CURSOR)
573                 need_update = NONE;
574         bv->owner()->view_state_changed();
575         bv->owner()->updateMenubar();
576         bv->owner()->updateToolbar();
577         if (old_par != cpar(bv)) {
578                 bv->owner()->setLayout(cpar(bv)->layout()->name());
579                 old_par = cpar(bv);
580         }
581 }
582
583
584 string const InsetText::editMessage() const
585 {
586         return _("Opened Text Inset");
587 }
588
589
590 void InsetText::edit(BufferView * bv, int x, int y, mouse_button::state button)
591 {
592         UpdatableInset::edit(bv, x, y, button);
593
594         if (!bv->lockInset(this)) {
595                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
596                 return;
597         }
598         locked = true;
599         the_locking_inset = 0;
600         inset_pos = inset_x = inset_y = 0;
601         inset_boundary = false;
602         inset_par = 0;
603         old_par = 0;
604         int tmp_y = (y < 0) ? 0 : y;
605         bool clear = false;
606         if (!lt) {
607                 lt = getLyXText(bv);
608                 clear = true;
609         }
610         // we put here -1 and not button as now the button in the
611         // edit call should not be needed we will fix this in 1.3.x
612         // cycle hopefully (Jug 20020509)
613         // FIXME: GUII I've changed this to none: probably WRONG
614         if (!checkAndActivateInset(bv, x, tmp_y, mouse_button::none)) {
615                 lt->setCursorFromCoordinates(x - drawTextXOffset,
616                                             y + insetAscent);
617                 lt->cursor.x_fix(lt->cursor.x());
618         }
619         lt->clearSelection();
620         finishUndo();
621         // If the inset is empty set the language of the current font to the
622         // language to the surronding text (if different).
623         if (paragraphs.begin()->empty() && !paragraphs.begin()->next() &&
624                 bv->getParentLanguage(this) != lt->current_font.language())
625         {
626                 LyXFont font(LyXFont::ALL_IGNORE);
627                 font.setLanguage(bv->getParentLanguage(this));
628                 setFont(bv, font, false);
629         }
630         if (clear)
631                 lt = 0;
632
633         int code = CURSOR;
634         if (drawFrame_ == LOCKED)
635                 code = CURSOR|DRAW_FRAME;
636         updateLocal(bv, code, false);
637         showInsetCursor(bv);
638
639         // Tell the paragraph dialog that we've entered an insettext.
640         bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
641 }
642
643
644 void InsetText::edit(BufferView * bv, bool front)
645 {
646         UpdatableInset::edit(bv, front);
647
648         if (!bv->lockInset(this)) {
649                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
650                 return;
651         }
652         locked = true;
653         the_locking_inset = 0;
654         inset_pos = inset_x = inset_y = 0;
655         inset_boundary = false;
656         inset_par = 0;
657         old_par = 0;
658         bool clear = false;
659         if (!lt) {
660                 lt = getLyXText(bv);
661                 clear = true;
662         }
663         if (front)
664                 lt->setCursor(&*(paragraphs.begin()), 0);
665         else {
666                 ParagraphList::iterator it = paragraphs.begin();
667                 ParagraphList::iterator end = paragraphs.end();
668                 while (boost::next(it) != end)
669                         ++it;
670 //              int const pos = (p->size() ? p->size()-1 : p->size());
671                 lt->setCursor(&*it, it->size());
672         }
673         lt->clearSelection();
674         finishUndo();
675         // If the inset is empty set the language of the current font to the
676         // language to the surronding text (if different).
677         if (paragraphs.begin()->empty() && !paragraphs.begin()->next() &&
678                 bv->getParentLanguage(this) != lt->current_font.language()) {
679                 LyXFont font(LyXFont::ALL_IGNORE);
680                 font.setLanguage(bv->getParentLanguage(this));
681                 setFont(bv, font, false);
682         }
683         if (clear)
684                 lt = 0;
685         int code = CURSOR;
686         if (drawFrame_ == LOCKED)
687                 code = CURSOR|DRAW_FRAME;
688         updateLocal(bv, code, false);
689         showInsetCursor(bv);
690 }
691
692
693 void InsetText::insetUnlock(BufferView * bv)
694 {
695         if (the_locking_inset) {
696                 the_locking_inset->insetUnlock(bv);
697                 the_locking_inset = 0;
698                 updateLocal(bv, CURSOR_PAR, false);
699         }
700         hideInsetCursor(bv);
701         no_selection = true;
702         locked = false;
703         int code = NONE;
704         bool clear = false;
705
706         if (!lt) {
707                 lt = getLyXText(bv);
708                 clear = true;
709         }
710         if (lt->selection.set()) {
711                 lt->clearSelection();
712                 code = FULL;
713         } else if (owner()) {
714                 bv->owner()->setLayout(owner()->getLyXText(bv)
715                                        ->cursor.par()->layout()->name());
716         } else
717                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
718         // hack for deleteEmptyParMech
719         if (!paragraphs.begin()->empty()) {
720                 lt->setCursor(&*(paragraphs.begin()), 0);
721         } else if (paragraphs.begin()->next()) {
722                 lt->setCursor(paragraphs.begin()->next(), 0);
723         }
724         if (clear)
725                 lt = 0;
726 #if 0
727         updateLocal(bv, code, false);
728 #else
729         if (code != NONE)
730                 setUpdateStatus(bv, code);
731 #endif
732 }
733
734
735 void InsetText::lockInset(BufferView * bv)
736 {
737         locked = true;
738         the_locking_inset = 0;
739         inset_pos = inset_x = inset_y = 0;
740         inset_boundary = false;
741         inset_par = 0;
742         old_par = 0;
743         bool clear = false;
744         if (!lt) {
745                 lt = getLyXText(bv);
746                 clear = true;
747         }
748         lt->setCursor(&*(paragraphs.begin()), 0);
749         lt->clearSelection();
750         finishUndo();
751         // If the inset is empty set the language of the current font to the
752         // language to the surronding text (if different).
753         if (paragraphs.begin()->empty() && !paragraphs.begin()->next() &&
754                 bv->getParentLanguage(this) != lt->current_font.language()) {
755                 LyXFont font(LyXFont::ALL_IGNORE);
756                 font.setLanguage(bv->getParentLanguage(this));
757                 setFont(bv, font, false);
758         }
759         if (clear)
760                 lt = 0;
761         int code = CURSOR;
762         if (drawFrame_ == LOCKED)
763                 code = CURSOR|DRAW_FRAME;
764         setUpdateStatus(bv, code);
765 }
766
767
768 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
769 {
770         the_locking_inset = inset;
771         inset_x = cix(bv) - top_x + drawTextXOffset;
772         inset_y = ciy(bv) + drawTextYOffset;
773         inset_pos = cpos(bv);
774         inset_par = cpar(bv);
775         inset_boundary = cboundary(bv);
776         updateLocal(bv, CURSOR, false);
777 }
778
779
780 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
781 {
782         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
783                               << inset << "): ";
784         if (!inset)
785                 return false;
786         if (!the_locking_inset) {
787                 Paragraph * p = &*(paragraphs.begin());
788                 int const id = inset->id();
789                 while(p) {
790                         InsetList::iterator it =
791                                 p->insetlist.begin();
792                         InsetList::iterator const end =
793                                 p->insetlist.end();
794                         for (; it != end; ++it) {
795                                 if (it.getInset() == inset) {
796                                         getLyXText(bv)->setCursorIntern(p, it.getPos());
797                                         lockInset(bv, inset);
798                                         return true;
799                                 }
800                                 if (it.getInset()->getInsetFromID(id)) {
801                                         getLyXText(bv)->setCursorIntern(p, it.getPos());
802                                         it.getInset()->edit(bv);
803                                         return the_locking_inset->lockInsetInInset(bv, inset);
804                                 }
805                         }
806                         p = p->next();
807                 }
808                 return false;
809         }
810         if (inset == cpar(bv)->getInset(cpos(bv))) {
811                 lyxerr[Debug::INSETS] << "OK" << endl;
812                 lockInset(bv, inset);
813                 return true;
814         } else if (the_locking_inset && (the_locking_inset == inset)) {
815                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
816                         lyxerr[Debug::INSETS] << "OK" << endl;
817                         inset_x = cix(bv) - top_x + drawTextXOffset;
818                         inset_y = ciy(bv) + drawTextYOffset;
819                 } else {
820                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
821                 }
822         } else if (the_locking_inset) {
823                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
824                 return the_locking_inset->lockInsetInInset(bv, inset);
825         }
826         lyxerr[Debug::INSETS] << "NOT OK" << endl;
827         return false;
828 }
829
830
831 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
832                                    bool lr)
833 {
834         if (!the_locking_inset)
835                 return false;
836         if (the_locking_inset == inset) {
837                 the_locking_inset->insetUnlock(bv);
838                 getLyXText(bv)->updateInset(inset);
839                 the_locking_inset = 0;
840                 if (lr)
841                         moveRightIntern(bv, true, false);
842                 old_par = 0; // force layout setting
843                 if (scroll())
844                         scroll(bv, 0.0F);
845                 else
846                         updateLocal(bv, CURSOR, false);
847                 return true;
848         }
849         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
850 }
851
852
853 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
854 {
855         if (!autoBreakRows && paragraphs.begin()->next())
856                 collapseParagraphs(bv);
857         if (inset == this)
858                 return true;
859         bool clear = false;
860         if (!lt) {
861                 lt = getLyXText(bv);
862                 clear = true;
863         }
864         if (inset->owner() != this) {
865                 int ustat = CURSOR_PAR;
866                 bool found = false;
867                 UpdatableInset * tl_inset = the_locking_inset;
868                 if (tl_inset)
869                         found = tl_inset->updateInsetInInset(bv, inset);
870                 if (!found) {
871                         tl_inset = static_cast<UpdatableInset *>(inset);
872                         while(tl_inset->owner() && tl_inset->owner() != this)
873                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
874                         if (!tl_inset->owner())
875                                 return false;
876                         found = tl_inset->updateInsetInInset(bv, inset);
877                         ustat = FULL;
878                 }
879                 if (found)
880                         lt->updateInset(tl_inset);
881                 if (clear)
882                         lt = 0;
883                 if (found)
884                         setUpdateStatus(bv, ustat);
885                 return found;
886         }
887         bool found = lt->updateInset(inset);
888         if (clear)
889                 lt = 0;
890         if (found) {
891                 setUpdateStatus(bv, CURSOR_PAR);
892                 if (the_locking_inset &&
893                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
894                 {
895                         inset_x = cix(bv) - top_x + drawTextXOffset;
896                         inset_y = ciy(bv) + drawTextYOffset;
897                 }
898         }
899         return found;
900 }
901
902
903 void InsetText::lfunMousePress(FuncRequest const & cmd)
904 {
905         no_selection = true;
906
907         // use this to check mouse motion for selection!
908         mouse_x = cmd.x;
909         mouse_y = cmd.y;
910
911         BufferView * bv = cmd.view();
912         FuncRequest cmd1 = cmd;
913         cmd1.x -= inset_x;
914         cmd1.y -= inset_y;
915         if (!locked)
916                 lockInset(bv);
917
918         int tmp_x = cmd.x - drawTextXOffset;
919         int tmp_y = cmd.y + insetAscent - getLyXText(bv)->top_y();
920         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
921
922         hideInsetCursor(bv);
923         if (the_locking_inset) {
924                 if (the_locking_inset == inset) {
925                         the_locking_inset->localDispatch(cmd1);
926                         return;
927                 }
928                 // otherwise only unlock the_locking_inset
929                 the_locking_inset->insetUnlock(bv);
930                 the_locking_inset = 0;
931         }
932         if (!inset)
933                 no_selection = false;
934
935         if (bv->theLockingInset()) {
936                 if (isHighlyEditableInset(inset)) {
937                         // We just have to lock the inset before calling a
938                         // PressEvent on it!
939                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
940                         if (!bv->lockInset(uinset)) {
941                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
942                         }
943                         inset->localDispatch(cmd1);
944                         if (the_locking_inset)
945                                 updateLocal(bv, CURSOR, false);
946                         return;
947                 }
948         }
949         if (!inset) {
950                 bool paste_internally = false;
951                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
952                         localDispatch(FuncRequest(bv, LFUN_COPY));
953                         paste_internally = true;
954                 }
955                 bool clear = false;
956                 if (!lt) {
957                         lt = getLyXText(bv);
958                         clear = true;
959                 }
960                 int old_top_y = lt->top_y();
961
962                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
963                                              cmd.y + insetAscent);
964                 // set the selection cursor!
965                 lt->selection.cursor = lt->cursor;
966                 lt->cursor.x_fix(lt->cursor.x());
967
968                 if (lt->selection.set()) {
969                         lt->clearSelection();
970                         updateLocal(bv, FULL, false);
971                 } else {
972                         lt->clearSelection();
973                         updateLocal(bv, CURSOR, false);
974                 }
975
976                 if (clear)
977                         lt = 0;
978
979                 bv->owner()->setLayout(cpar(bv)->layout()->name());
980
981                 // we moved the view we cannot do mouse selection in this case!
982                 if (getLyXText(bv)->top_y() != old_top_y)
983                         no_selection = true;
984                 old_par = cpar(bv);
985                 // Insert primary selection with middle mouse
986                 // if there is a local selection in the current buffer,
987                 // insert this
988                 if (cmd.button() == mouse_button::button2) {
989                         if (paste_internally)
990                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
991                         else
992                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
993                 }
994         } else {
995                 getLyXText(bv)->clearSelection();
996         }
997         showInsetCursor(bv);
998 }
999
1000
1001 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
1002 {
1003         BufferView * bv = cmd.view();
1004         FuncRequest cmd1 = cmd;
1005         cmd1.x -= inset_x;
1006         cmd1.y -= inset_y;
1007
1008         no_selection = true;
1009         if (the_locking_inset)
1010                 return the_locking_inset->localDispatch(cmd1);
1011
1012         int tmp_x = cmd.x - drawTextXOffset;
1013         int tmp_y = cmd.y + insetAscent - getLyXText(bv)->top_y();
1014         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
1015         bool ret = false;
1016         if (inset) {
1017                 if (isHighlyEditableInset(inset))
1018                         ret = inset->localDispatch(cmd1);
1019                 else {
1020                         inset_x = cix(bv) - top_x + drawTextXOffset;
1021                         inset_y = ciy(bv) + drawTextYOffset;
1022                         cmd1.x = cmd.x - inset_x;
1023                         cmd1.y = cmd.x - inset_y;
1024 // note that we should do ret = inset->localDispatch(cmd1)
1025 // and fix this instead (Alfredo);
1026                         ret = true;
1027                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
1028                 }
1029                 updateLocal(bv, CURSOR_PAR, false);
1030         }
1031         return ret;
1032 }
1033
1034
1035 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
1036 {
1037         FuncRequest cmd1 = cmd;
1038         cmd1.x -= inset_x;
1039         cmd1.y -= inset_y;
1040
1041         if (the_locking_inset) {
1042                 the_locking_inset->localDispatch(cmd1);
1043                 return;
1044         }
1045
1046         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
1047                 return;
1048
1049         BufferView * bv = cmd.view();
1050         bool clear = false;
1051         if (!lt) {
1052                 lt = getLyXText(bv);
1053                 clear = true;
1054         }
1055         hideInsetCursor(bv);
1056         LyXCursor cur = lt->cursor;
1057         lt->setCursorFromCoordinates
1058                 (cmd.x - drawTextXOffset, cmd.y + insetAscent);
1059         lt->cursor.x_fix(lt->cursor.x());
1060         if (cur == lt->cursor) {
1061                 if (clear)
1062                         lt = 0;
1063                 return;
1064         }
1065         lt->setSelection();
1066         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
1067                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
1068         if (clear)
1069                 lt = 0;
1070         if (flag) {
1071                 updateLocal(bv, SELECTION, false);
1072         }
1073         showInsetCursor(bv);
1074 }
1075
1076
1077 Inset::RESULT InsetText::localDispatch(FuncRequest const & ev)
1078 {
1079         BufferView * bv = ev.view();
1080         switch (ev.action) {
1081                 case LFUN_MOUSE_PRESS:
1082                         lfunMousePress(ev);
1083                         return DISPATCHED;
1084                 case LFUN_MOUSE_MOTION:
1085                         lfunMouseMotion(ev);
1086                         return DISPATCHED;
1087                 case LFUN_MOUSE_RELEASE:
1088                         return lfunMouseRelease(ev) ? DISPATCHED : UNDISPATCHED;
1089                 default:
1090                         break;
1091         }
1092
1093         bool was_empty = (paragraphs.begin()->empty() && !paragraphs.begin()->next());
1094         no_selection = false;
1095         RESULT result = UpdatableInset::localDispatch(ev);
1096         if (result != UNDISPATCHED)
1097                 return DISPATCHED;
1098
1099         result = DISPATCHED;
1100         if (ev.action < 0 && ev.argument.empty())
1101                 return FINISHED;
1102
1103         if (the_locking_inset) {
1104                 result = the_locking_inset->localDispatch(ev);
1105                 if (result == DISPATCHED_NOUPDATE)
1106                         return result;
1107                 else if (result == DISPATCHED) {
1108                         updateLocal(bv, CURSOR_PAR, false);
1109                         return result;
1110                 } else if (result >= FINISHED) {
1111                         switch (result) {
1112                         case FINISHED_RIGHT:
1113                                 moveRightIntern(bv, false, false);
1114                                 result = DISPATCHED;
1115                                 break;
1116                         case FINISHED_UP:
1117                                 if ((result = moveUp(bv)) >= FINISHED) {
1118                                         updateLocal(bv, CURSOR, false);
1119                                         bv->unlockInset(this);
1120                                 }
1121                                 break;
1122                         case FINISHED_DOWN:
1123                                 if ((result = moveDown(bv)) >= FINISHED) {
1124                                         updateLocal(bv, CURSOR, false);
1125                                         bv->unlockInset(this);
1126                                 }
1127                                 break;
1128                         default:
1129                                 result = DISPATCHED;
1130                                 break;
1131                         }
1132                         the_locking_inset = 0;
1133                         updateLocal(bv, CURSOR, false);
1134                         return result;
1135                 }
1136         }
1137         hideInsetCursor(bv);
1138         bool clear = false;
1139         if (!lt) {
1140                 lt = getLyXText(bv);
1141                 clear = true;
1142         }
1143         int updwhat = 0;
1144         int updflag = false;
1145
1146         // what type of update to do on a cursor movement
1147         int cursor_update = CURSOR;
1148
1149         if (lt->selection.set())
1150                 cursor_update = SELECTION;
1151
1152         switch (ev.action) {
1153
1154         // Normal chars
1155         case LFUN_SELFINSERT:
1156                 if (bv->buffer()->isReadonly()) {
1157 //          setErrorMessage(N_("Document is read only"));
1158                         break;
1159                 }
1160                 if (!ev.argument.empty()) {
1161                         /* Automatically delete the currently selected
1162                          * text and replace it with what is being
1163                          * typed in now. Depends on lyxrc settings
1164                          * "auto_region_delete", which defaults to
1165                          * true (on). */
1166 #if 0
1167                         // This should not be needed here and is also WRONG!
1168                         setUndo(bv, Undo::INSERT,
1169                                 lt->cursor.par(), lt->cursor.par()->next());
1170 #endif
1171                         bv->switchKeyMap();
1172                         if (lyxrc.auto_region_delete) {
1173                                 if (lt->selection.set()) {
1174                                         lt->cutSelection(false, false);
1175                                 }
1176                         }
1177                         lt->clearSelection();
1178                         for (string::size_type i = 0; i < ev.argument.length(); ++i) {
1179                                 bv->owner()->getIntl().getTransManager().
1180                                         TranslateAndInsert(ev.argument[i], lt);
1181                         }
1182                 }
1183                 lt->selection.cursor = lt->cursor;
1184                 updwhat = CURSOR | CURSOR_PAR;
1185                 updflag = true;
1186                 result = DISPATCHED_NOUPDATE;
1187                 break;
1188
1189         // cursor movements that need special handling
1190
1191         case LFUN_RIGHT:
1192                 result = moveRight(bv);
1193                 finishUndo();
1194                 updwhat = cursor_update;
1195                 break;
1196         case LFUN_LEFT:
1197                 finishUndo();
1198                 result = moveLeft(bv);
1199                 updwhat = cursor_update;
1200                 break;
1201         case LFUN_DOWN:
1202                 finishUndo();
1203                 result = moveDown(bv);
1204                 updwhat = cursor_update;
1205                 break;
1206         case LFUN_UP:
1207                 finishUndo();
1208                 result = moveUp(bv);
1209                 updwhat = cursor_update;
1210                 break;
1211
1212         case LFUN_PRIOR:
1213                 if (!crow(bv)->previous())
1214                         result = FINISHED_UP;
1215                 else {
1216                         lt->cursorPrevious();
1217                         lt->clearSelection();
1218                         result = DISPATCHED_NOUPDATE;
1219                 }
1220                 updwhat = cursor_update;
1221                 break;
1222
1223         case LFUN_NEXT:
1224                 if (!crow(bv)->next())
1225                         result = FINISHED_DOWN;
1226                 else {
1227                         lt->cursorNext();
1228                         lt->clearSelection();
1229                         result = DISPATCHED_NOUPDATE;
1230                 }
1231                 updwhat = cursor_update;
1232                 break;
1233
1234         case LFUN_BACKSPACE: {
1235                 if (lt->selection.set())
1236                         lt->cutSelection(true, false);
1237                 else
1238                         lt->backspace();
1239                 updwhat = CURSOR_PAR;
1240                 updflag = true;
1241                 break;
1242         }
1243
1244         case LFUN_DELETE: {
1245                 if (lt->selection.set()) {
1246                         lt->cutSelection(true, false);
1247                 } else {
1248                         lt->Delete();
1249                 }
1250                 updwhat = CURSOR_PAR;
1251                 updflag = true;
1252                 break;
1253         }
1254
1255         case LFUN_CUT: {
1256                 lt->cutSelection(bv);
1257                 updwhat = CURSOR_PAR;
1258                 updflag = true;
1259                 break;
1260         }
1261
1262         case LFUN_COPY:
1263                 finishUndo();
1264                 lt->copySelection();
1265                 updwhat = CURSOR_PAR;
1266                 break;
1267
1268         case LFUN_PASTESELECTION:
1269         {
1270                 string const clip(bv->getClipboard());
1271
1272                 if (clip.empty())
1273                         break;
1274                 if (ev.argument == "paragraph") {
1275                         lt->insertStringAsParagraphs(clip);
1276                 } else {
1277                         lt->insertStringAsLines(clip);
1278                 }
1279                 // bug 393
1280                 lt->clearSelection();
1281
1282                 updwhat = CURSOR_PAR;
1283                 updflag = true;
1284                 break;
1285         }
1286
1287         case LFUN_PASTE: {
1288                 if (!autoBreakRows) {
1289                         if (CutAndPaste::nrOfParagraphs() > 1) {
1290 #ifdef WITH_WARNINGS
1291 #warning FIXME horrendously bad UI
1292 #endif
1293                                 Alert::alert(_("Impossible operation!"),
1294                                                    _("Cannot include more than one paragraph!"),
1295                                                    _("Sorry."));
1296                                 break;
1297                         }
1298                 }
1299
1300                 lt->pasteSelection();
1301                 // bug 393
1302                 lt->clearSelection();
1303                 updwhat = CURSOR_PAR;
1304                 updflag = true;
1305                 break;
1306         }
1307
1308         case LFUN_BREAKPARAGRAPH:
1309                 if (!autoBreakRows) {
1310                         result = DISPATCHED;
1311                         break;
1312                 }
1313                 lt->breakParagraph(paragraphs, 0);
1314                 updwhat = CURSOR | FULL;
1315                 updflag = true;
1316                 break;
1317
1318         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1319                 if (!autoBreakRows) {
1320                         result = DISPATCHED;
1321                         break;
1322                 }
1323                 lt->breakParagraph(paragraphs, 1);
1324                 updwhat = CURSOR | FULL;
1325                 updflag = true;
1326                 break;
1327
1328         case LFUN_BREAKLINE: {
1329                 if (!autoBreakRows) {
1330                         result = DISPATCHED;
1331                         break;
1332                 }
1333
1334                 lt->insertInset(new InsetNewline);
1335                 updwhat = CURSOR | CURSOR_PAR;
1336                 updflag = true;
1337                 break;
1338         }
1339
1340         case LFUN_LAYOUT:
1341                 // do not set layouts on non breakable textinsets
1342                 if (autoBreakRows) {
1343                         string cur_layout = cpar(bv)->layout()->name();
1344
1345                         // Derive layout number from given argument (string)
1346                         // and current buffer's textclass (number). */
1347                         LyXTextClass const & tclass =
1348                                 bv->buffer()->params.getLyXTextClass();
1349                         string layout = ev.argument;
1350                         bool hasLayout = tclass.hasLayout(layout);
1351
1352                         // If the entry is obsolete, use the new one instead.
1353                         if (hasLayout) {
1354                                 string const & obs =
1355                                         tclass[layout]->obsoleted_by();
1356                                 if (!obs.empty())
1357                                         layout = obs;
1358                         }
1359
1360                         // see if we found the layout number:
1361                         if (!hasLayout) {
1362                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + ev.argument + N_(" not known"));
1363                                 bv->owner()->dispatch(lf);
1364                                 break;
1365                         }
1366
1367                         if (cur_layout != layout) {
1368                                 cur_layout = layout;
1369                                 lt->setLayout(layout);
1370                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1371                                 updwhat = CURSOR_PAR;
1372                                 updflag = true;
1373                         }
1374                 } else {
1375                         // reset the layout box
1376                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1377                 }
1378                 break;
1379         case LFUN_PARAGRAPH_SPACING:
1380                 // This one is absolutely not working. When fiddling with this
1381                 // it also seems to me that the paragraphs inside the insettext
1382                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1383                 // FIXME: how old is this comment ? ...
1384         {
1385                 Paragraph * par = lt->cursor.par();
1386                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
1387                 float cur_value = 1.0;
1388                 if (cur_spacing == Spacing::Other) {
1389                         cur_value = par->params().spacing().getValue();
1390                 }
1391
1392                 istringstream istr(ev.argument.c_str());
1393                 string tmp;
1394                 istr >> tmp;
1395                 Spacing::Space new_spacing = cur_spacing;
1396                 float new_value = cur_value;
1397                 if (tmp.empty()) {
1398                         lyxerr << "Missing argument to `paragraph-spacing'"
1399                                    << endl;
1400                 } else if (tmp == "single") {
1401                         new_spacing = Spacing::Single;
1402                 } else if (tmp == "onehalf") {
1403                         new_spacing = Spacing::Onehalf;
1404                 } else if (tmp == "double") {
1405                         new_spacing = Spacing::Double;
1406                 } else if (tmp == "other") {
1407                         new_spacing = Spacing::Other;
1408                         float tmpval = 0.0;
1409                         istr >> tmpval;
1410                         lyxerr << "new_value = " << tmpval << endl;
1411                         if (tmpval != 0.0)
1412                                 new_value = tmpval;
1413                 } else if (tmp == "default") {
1414                         new_spacing = Spacing::Default;
1415                 } else {
1416                         lyxerr << _("Unknown spacing argument: ")
1417                                    << ev.argument << endl;
1418                 }
1419                 if (cur_spacing != new_spacing || cur_value != new_value) {
1420                         par->params().spacing(Spacing(new_spacing, new_value));
1421                         updwhat = CURSOR_PAR;
1422                         updflag = true;
1423                 }
1424         }
1425         break;
1426
1427         // These need to do repaints but don't require
1428         // special handling otherwise. A *lot* of the
1429         // above could probably be done similarly ...
1430
1431         case LFUN_HOME:
1432         case LFUN_END:
1433         case LFUN_WORDLEFT:
1434         case LFUN_WORDRIGHT:
1435         // these two are really unhandled ...
1436         case LFUN_ENDBUF:
1437         case LFUN_BEGINNINGBUF:
1438                 updwhat = cursor_update;
1439                 if (!bv->dispatch(ev))
1440                         result = UNDISPATCHED;
1441                 break;
1442
1443         case LFUN_RIGHTSEL:
1444         case LFUN_UPSEL:
1445         case LFUN_DOWNSEL:
1446         case LFUN_LEFTSEL:
1447         case LFUN_HOMESEL:
1448         case LFUN_ENDSEL:
1449         case LFUN_WORDLEFTSEL:
1450         case LFUN_WORDRIGHTSEL:
1451                 updwhat = SELECTION;
1452
1453                 // fallthrough
1454
1455         default:
1456                 if (!bv->dispatch(ev))
1457                         result = UNDISPATCHED;
1458                 break;
1459         }
1460
1461         if (clear)
1462                 lt = 0;
1463         if (updwhat > 0)
1464                 updateLocal(bv, updwhat, updflag);
1465         /// If the action has deleted all text in the inset, we need to change the
1466         // language to the language of the surronding text.
1467         if (!was_empty && paragraphs.begin()->empty() && !paragraphs.begin()->next()) {
1468                 LyXFont font(LyXFont::ALL_IGNORE);
1469                 font.setLanguage(bv->getParentLanguage(this));
1470                 setFont(bv, font, false);
1471         }
1472
1473         if (result >= FINISHED)
1474                 bv->unlockInset(this);
1475
1476         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1477                 result = DISPATCHED;
1478         return result;
1479 }
1480
1481
1482 int InsetText::latex(Buffer const * buf, ostream & os,
1483                      bool moving_arg, bool) const
1484 {
1485         TexRow texrow;
1486         latexParagraphs(buf, paragraphs,
1487                         paragraphs.begin(), paragraphs.end(),
1488                         os, texrow, moving_arg);
1489         return texrow.rows();
1490 }
1491
1492
1493 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1494 {
1495         unsigned int lines = 0;
1496
1497         ParagraphList::iterator beg = paragraphs.begin();
1498         ParagraphList::iterator end = paragraphs.end();
1499         ParagraphList::iterator it = beg;
1500         for (; it != end; ++it) {
1501                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1502                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1503                 os << tmp;
1504         }
1505         return lines;
1506 }
1507
1508
1509 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1510 {
1511         Paragraph * p = &*(paragraphs.begin());
1512         unsigned int lines = 0;
1513
1514         vector<string> environment_stack(10);
1515         vector<string> environment_inner(10);
1516
1517         int const command_depth = 0;
1518         string item_name;
1519
1520         Paragraph::depth_type depth = 0; // paragraph depth
1521
1522         while (p) {
1523                 string sgmlparam;
1524                 int desc_on = 0; // description mode
1525
1526                 LyXLayout_ptr const & style = p->layout();
1527
1528                 // environment tag closing
1529                 for (; depth > p->params().depth(); --depth) {
1530                         if (environment_inner[depth] != "!-- --") {
1531                                 item_name = "listitem";
1532                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1533                                 if (environment_inner[depth] == "varlistentry")
1534                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1535                         }
1536                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1537                         environment_stack[depth].erase();
1538                         environment_inner[depth].erase();
1539                 }
1540
1541                 if (depth == p->params().depth()
1542                    && environment_stack[depth] != style->latexname()
1543                    && !environment_stack[depth].empty()) {
1544                         if (environment_inner[depth] != "!-- --") {
1545                                 item_name= "listitem";
1546                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1547                                 if (environment_inner[depth] == "varlistentry")
1548                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1549                         }
1550
1551                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1552
1553                         environment_stack[depth].erase();
1554                         environment_inner[depth].erase();
1555                 }
1556
1557                 // Write opening SGML tags.
1558                 switch (style->latextype) {
1559                 case LATEX_PARAGRAPH:
1560                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1561                         break;
1562
1563                 case LATEX_COMMAND:
1564                         buf->sgmlError(p, 0,  _("Error: LatexType Command not allowed here.\n"));
1565                         return -1;
1566                         break;
1567
1568                 case LATEX_ENVIRONMENT:
1569                 case LATEX_ITEM_ENVIRONMENT:
1570                         if (depth < p->params().depth()) {
1571                                 depth = p->params().depth();
1572                                 environment_stack[depth].erase();
1573                         }
1574
1575                         if (environment_stack[depth] != style->latexname()) {
1576                                 if (environment_stack.size() == depth + 1) {
1577                                         environment_stack.push_back("!-- --");
1578                                         environment_inner.push_back("!-- --");
1579                                 }
1580                                 environment_stack[depth] = style->latexname();
1581                                 environment_inner[depth] = "!-- --";
1582                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1583                         } else {
1584                                 if (environment_inner[depth] != "!-- --") {
1585                                         item_name= "listitem";
1586                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1587                                         if (environment_inner[depth] == "varlistentry")
1588                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1589                                 }
1590                         }
1591
1592                         if (style->latextype == LATEX_ENVIRONMENT) {
1593                                 if (!style->latexparam().empty()) {
1594                                         if (style->latexparam() == "CDATA")
1595                                                 os << "<![CDATA[";
1596                                         else
1597                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1598                                 }
1599                                 break;
1600                         }
1601
1602                         desc_on = (style->labeltype == LABEL_MANUAL);
1603
1604                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1605                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1606
1607                         item_name = desc_on ? "term" : "para";
1608                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1609
1610                         break;
1611                 default:
1612                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1613                         break;
1614                 }
1615
1616                 buf->simpleDocBookOnePar(os, p, desc_on, depth + 1 + command_depth);
1617                 p = p->next();
1618
1619                 string end_tag;
1620                 // write closing SGML tags
1621                 switch (style->latextype) {
1622                 case LATEX_ENVIRONMENT:
1623                         if (!style->latexparam().empty()) {
1624                                 if (style->latexparam() == "CDATA")
1625                                         os << "]]>";
1626                                 else
1627                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1628                         }
1629                         break;
1630                 case LATEX_ITEM_ENVIRONMENT:
1631                         if (desc_on == 1) break;
1632                         end_tag= "para";
1633                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1634                         break;
1635                 case LATEX_PARAGRAPH:
1636                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1637                         break;
1638                 default:
1639                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1640                         break;
1641                 }
1642         }
1643
1644         // Close open tags
1645         for (int d = depth; d >= 0; --d) {
1646                 if (!environment_stack[depth].empty()) {
1647                         if (environment_inner[depth] != "!-- --") {
1648                                 item_name = "listitem";
1649                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1650                                if (environment_inner[depth] == "varlistentry")
1651                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1652                         }
1653
1654                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1655                 }
1656         }
1657
1658         return lines;
1659 }
1660
1661
1662 void InsetText::validate(LaTeXFeatures & features) const
1663 {
1664         for_each(paragraphs.begin(), paragraphs.end(),
1665                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1666 }
1667
1668
1669 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1670 {
1671         if (the_locking_inset) {
1672                 the_locking_inset->getCursorPos(bv, x, y);
1673                 return;
1674         }
1675         x = cx(bv) - top_x - TEXT_TO_INSET_OFFSET;
1676         y = cy(bv) - TEXT_TO_INSET_OFFSET;
1677 }
1678
1679
1680 int InsetText::insetInInsetY() const
1681 {
1682         if (!the_locking_inset)
1683                 return 0;
1684
1685         return (inset_y + the_locking_inset->insetInInsetY());
1686 }
1687
1688
1689 void InsetText::toggleInsetCursor(BufferView * bv)
1690 {
1691         if (the_locking_inset) {
1692                 the_locking_inset->toggleInsetCursor(bv);
1693                 return;
1694         }
1695
1696         LyXFont const font(getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv)));
1697
1698         int const asc = font_metrics::maxAscent(font);
1699         int const desc = font_metrics::maxDescent(font);
1700
1701         if (isCursorVisible())
1702                 bv->hideLockedInsetCursor();
1703         else
1704                 bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1705         toggleCursorVisible();
1706 }
1707
1708
1709 void InsetText::showInsetCursor(BufferView * bv, bool show)
1710 {
1711         if (the_locking_inset) {
1712                 the_locking_inset->showInsetCursor(bv, show);
1713                 return;
1714         }
1715         if (!isCursorVisible()) {
1716                 LyXFont const font =
1717                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1718
1719                 int const asc = font_metrics::maxAscent(font);
1720                 int const desc = font_metrics::maxDescent(font);
1721
1722                 bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1723                 if (show)
1724                         bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1725                 setCursorVisible(true);
1726         }
1727 }
1728
1729
1730 void InsetText::hideInsetCursor(BufferView * bv)
1731 {
1732         if (isCursorVisible()) {
1733                 bv->hideLockedInsetCursor();
1734                 setCursorVisible(false);
1735         }
1736         if (the_locking_inset)
1737                 the_locking_inset->hideInsetCursor(bv);
1738 }
1739
1740
1741 void InsetText::fitInsetCursor(BufferView * bv) const
1742 {
1743         if (the_locking_inset) {
1744                 the_locking_inset->fitInsetCursor(bv);
1745                 return;
1746         }
1747         LyXFont const font =
1748                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1749
1750         int const asc = font_metrics::maxAscent(font);
1751         int const desc = font_metrics::maxDescent(font);
1752
1753         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1754                 need_update |= FULL;
1755 }
1756
1757
1758 Inset::RESULT
1759 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1760 {
1761         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1762                 return moveLeftIntern(bv, false, activate_inset, selecting);
1763         else
1764                 return moveRightIntern(bv, true, activate_inset, selecting);
1765 }
1766
1767
1768 Inset::RESULT
1769 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1770 {
1771         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1772                 return moveRightIntern(bv, true, activate_inset, selecting);
1773         else
1774                 return moveLeftIntern(bv, false, activate_inset, selecting);
1775 }
1776
1777
1778 Inset::RESULT
1779 InsetText::moveRightIntern(BufferView * bv, bool front,
1780                            bool activate_inset, bool selecting)
1781 {
1782         if (!cpar(bv)->next() && (cpos(bv) >= cpar(bv)->size()))
1783                 return FINISHED_RIGHT;
1784         if (activate_inset && checkAndActivateInset(bv, front))
1785                 return DISPATCHED;
1786         getLyXText(bv)->cursorRight(bv);
1787         if (!selecting)
1788                 getLyXText(bv)->clearSelection();
1789         return DISPATCHED_NOUPDATE;
1790 }
1791
1792
1793 Inset::RESULT
1794 InsetText::moveLeftIntern(BufferView * bv, bool front,
1795                           bool activate_inset, bool selecting)
1796 {
1797         if (!cpar(bv)->previous() && (cpos(bv) <= 0))
1798                 return FINISHED;
1799         getLyXText(bv)->cursorLeft(bv);
1800         if (!selecting)
1801                 getLyXText(bv)->clearSelection();
1802         if (activate_inset && checkAndActivateInset(bv, front))
1803                 return DISPATCHED;
1804         return DISPATCHED_NOUPDATE;
1805 }
1806
1807
1808 Inset::RESULT InsetText::moveUp(BufferView * bv)
1809 {
1810         if (!crow(bv)->previous())
1811                 return FINISHED_UP;
1812         getLyXText(bv)->cursorUp(bv);
1813         getLyXText(bv)->clearSelection();
1814         return DISPATCHED_NOUPDATE;
1815 }
1816
1817
1818 Inset::RESULT InsetText::moveDown(BufferView * bv)
1819 {
1820         if (!crow(bv)->next())
1821                 return FINISHED_DOWN;
1822         getLyXText(bv)->cursorDown(bv);
1823         getLyXText(bv)->clearSelection();
1824         return DISPATCHED_NOUPDATE;
1825 }
1826
1827
1828 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1829 {
1830         if (the_locking_inset) {
1831                 if (the_locking_inset->insetAllowed(inset))
1832                         return the_locking_inset->insertInset(bv, inset);
1833                 return false;
1834         }
1835         inset->setOwner(this);
1836         hideInsetCursor(bv);
1837         getLyXText(bv)->insertInset(inset);
1838         bv->fitCursor();
1839         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1840         return true;
1841 }
1842
1843
1844 bool InsetText::insetAllowed(Inset::Code code) const
1845 {
1846         // in_insetAllowed is a really gross hack,
1847         // to allow us to call the owner's insetAllowed
1848         // without stack overflow, which can happen
1849         // when the owner uses InsetCollapsable::insetAllowed()
1850         bool ret = true;
1851         if (in_insetAllowed)
1852                 return ret;
1853         in_insetAllowed = true;
1854         if (the_locking_inset)
1855                 ret = the_locking_inset->insetAllowed(code);
1856         else if (owner())
1857                 ret = owner()->insetAllowed(code);
1858         in_insetAllowed = false;
1859         return ret;
1860 }
1861
1862
1863 UpdatableInset * InsetText::getLockingInset() const
1864 {
1865         return the_locking_inset ? the_locking_inset->getLockingInset() :
1866                 const_cast<InsetText *>(this);
1867 }
1868
1869
1870 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1871 {
1872         if (c == lyxCode())
1873                 return this;
1874         if (the_locking_inset)
1875                 return the_locking_inset->getFirstLockingInsetOfType(c);
1876         return 0;
1877 }
1878
1879
1880 bool InsetText::showInsetDialog(BufferView * bv) const
1881 {
1882         if (the_locking_inset)
1883                 return the_locking_inset->showInsetDialog(bv);
1884         return false;
1885 }
1886
1887
1888 vector<string> const InsetText::getLabelList() const
1889 {
1890         vector<string> label_list;
1891
1892         ParagraphList::iterator pit = paragraphs.begin();
1893         ParagraphList::iterator pend = paragraphs.end();
1894         for (; pit != pend; ++pit) {
1895                 InsetList::iterator beg = pit->insetlist.begin();
1896                 InsetList::iterator end = pit->insetlist.end();
1897                 for (; beg != end; ++beg) {
1898                         vector<string> const l = beg.getInset()->getLabelList();
1899                         label_list.insert(label_list.end(), l.begin(), l.end());
1900                 }
1901         }
1902         return label_list;
1903 }
1904
1905
1906 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1907                         bool selectall)
1908 {
1909         if (the_locking_inset) {
1910                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1911                 return;
1912         }
1913         if ((!paragraphs.begin()->next() && paragraphs.begin()->empty()) || cpar(bv)->empty()) {
1914                 getLyXText(bv)->setFont(font, toggleall);
1915                 return;
1916         }
1917         bool clear = false;
1918         if (!lt) {
1919                 lt = getLyXText(bv);
1920                 clear = true;
1921         }
1922         if (lt->selection.set()) {
1923                 setUndo(bv, Undo::EDIT, lt->cursor.par(), lt->cursor.par()->next());
1924         }
1925         if (selectall)
1926                 selectAll(bv);
1927         lt->toggleFree(font, toggleall);
1928         if (selectall)
1929                 lt->clearSelection();
1930         bv->fitCursor();
1931         bool flag = (selectall || lt->selection.set());
1932         if (clear)
1933                 lt = 0;
1934         if (flag)
1935                 updateLocal(bv, FULL, true);
1936         else
1937                 updateLocal(bv, CURSOR_PAR, true);
1938 }
1939
1940
1941 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1942 {
1943         if (cpar(bv)->isInset(cpos(bv))) {
1944                 Inset * inset =
1945                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1946                 if (!isHighlyEditableInset(inset))
1947                         return false;
1948                 inset->edit(bv, front);
1949                 if (!the_locking_inset)
1950                         return false;
1951                 updateLocal(bv, CURSOR, false);
1952                 return true;
1953         }
1954         return false;
1955 }
1956
1957
1958 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1959                                       mouse_button::state button)
1960 {
1961         x -= drawTextXOffset;
1962         int dummyx = x;
1963         int dummyy = y + insetAscent;
1964         Inset * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1965         // we only do the edit() call if the inset was hit by the mouse
1966         // or if it is a highly editable inset. So we should call this
1967         // function from our own edit with button < 0.
1968         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1969         // WRONG
1970         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1971                 return false;
1972
1973         if (inset) {
1974                 if (x < 0)
1975                         x = insetWidth;
1976                 if (y < 0)
1977                         y = insetDescent;
1978                 inset_x = cix(bv) - top_x + drawTextXOffset;
1979                 inset_y = ciy(bv) + drawTextYOffset;
1980                 inset->edit(bv, x - inset_x, y - inset_y, button);
1981                 if (!the_locking_inset)
1982                         return false;
1983                 updateLocal(bv, CURSOR, false);
1984                 return true;
1985         }
1986         return false;
1987 }
1988
1989
1990 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
1991 {
1992 #if 0
1993         int w = UpdatableInset::getMaxWidth(bv, inset);
1994         if (w < 0) {
1995                 return -1;
1996         }
1997         if (owner()) {
1998                 w = w - top_x + owner()->x();
1999                 return w;
2000         }
2001         w -= (2 * TEXT_TO_INSET_OFFSET);
2002         return w - top_x;
2003 #else
2004         return UpdatableInset::getMaxWidth(bv, inset);
2005 #endif
2006 }
2007
2008
2009 void InsetText::setParagraphData(Paragraph * p, bool same_id)
2010 {
2011         // we have to unlock any locked inset otherwise we're in troubles
2012         the_locking_inset = 0;
2013
2014         paragraphs.clear();
2015         paragraphs.set(new Paragraph(*p, same_id));
2016         paragraphs.begin()->setInsetOwner(this);
2017         Paragraph * np = &*(paragraphs.begin());
2018         while (p->next()) {
2019                 p = p->next();
2020                 np->next(new Paragraph(*p, same_id));
2021                 np->next()->previous(np);
2022                 np = np->next();
2023                 np->setInsetOwner(this);
2024         }
2025         reinitLyXText();
2026         need_update = INIT;
2027 }
2028
2029
2030 void InsetText::markNew(bool track_changes)
2031 {
2032         ParagraphList::iterator pit = paragraphs.begin();
2033         ParagraphList::iterator pend = paragraphs.end();
2034         for (; pit != pend; ++pit) {
2035                 if (track_changes) {
2036                         pit->trackChanges();
2037                 } else {
2038                         // no-op when not tracking
2039                         pit->cleanChanges();
2040                 }
2041         }
2042 }
2043
2044
2045 void InsetText::setText(string const & data, LyXFont const & font)
2046 {
2047         clear(false);
2048         for (unsigned int i = 0; i < data.length(); ++i)
2049                 paragraphs.begin()->insertChar(i, data[i], font);
2050         reinitLyXText();
2051 }
2052
2053
2054 void InsetText::setAutoBreakRows(bool flag)
2055 {
2056         if (flag != autoBreakRows) {
2057                 autoBreakRows = flag;
2058                 if (!flag)
2059                         removeNewlines();
2060                 need_update = INIT;
2061         }
2062 }
2063
2064
2065 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
2066 {
2067         if (how != drawFrame_) {
2068                 drawFrame_ = how;
2069                 if (bv)
2070                         updateLocal(bv, DRAW_FRAME, false);
2071         }
2072 }
2073
2074
2075 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2076 {
2077         if (frame_color != col) {
2078                 frame_color = col;
2079                 if (bv)
2080                         updateLocal(bv, DRAW_FRAME, false);
2081         }
2082 }
2083
2084
2085 int InsetText::cx(BufferView * bv) const
2086 {
2087         // we do nothing dangerous so we use a local cache
2088         LyXText * llt = getLyXText(bv);
2089         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2090         if (the_locking_inset) {
2091                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2092                                             llt->cursor.pos());
2093                 if (font.isVisibleRightToLeft())
2094                         x -= the_locking_inset->width(bv, font);
2095         }
2096         return x;
2097 }
2098
2099
2100 int InsetText::cix(BufferView * bv) const
2101 {
2102         // we do nothing dangerous so we use a local cache
2103         LyXText * llt = getLyXText(bv);
2104         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2105         if (the_locking_inset) {
2106                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2107                                             llt->cursor.pos());
2108                 if (font.isVisibleRightToLeft())
2109                         x -= the_locking_inset->width(bv, font);
2110         }
2111         return x;
2112 }
2113
2114
2115 int InsetText::cy(BufferView * bv) const
2116 {
2117         LyXFont font;
2118         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2119 }
2120
2121
2122 int InsetText::ciy(BufferView * bv) const
2123 {
2124         LyXFont font;
2125         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2126 }
2127
2128
2129 pos_type InsetText::cpos(BufferView * bv) const
2130 {
2131         return getLyXText(bv)->cursor.pos();
2132 }
2133
2134
2135 Paragraph * InsetText::cpar(BufferView * bv) const
2136 {
2137         return getLyXText(bv)->cursor.par();
2138 }
2139
2140
2141 bool InsetText::cboundary(BufferView * bv) const
2142 {
2143         return getLyXText(bv)->cursor.boundary();
2144 }
2145
2146
2147 Row * InsetText::crow(BufferView * bv) const
2148 {
2149         return getLyXText(bv)->cursor.row();
2150 }
2151
2152
2153 LyXText * InsetText::getLyXText(BufferView const * lbv,
2154                                 bool const recursive) const
2155 {
2156         if (cached_bview == lbv) {
2157                 if (recursive && the_locking_inset)
2158                         return the_locking_inset->getLyXText(lbv, true);
2159                 LyXText * lt = cached_text.get();
2160                 lyx::Assert(lt && lt->rows().begin()->par() == &*(paragraphs.begin()));
2161                 return lt;
2162         }
2163         // Super UGLY! (Lgb)
2164         BufferView * bv = const_cast<BufferView *>(lbv);
2165
2166         cached_bview = bv;
2167         Cache::iterator it = cache.find(bv);
2168
2169         if (it != cache.end()) {
2170                 if (do_reinit) {
2171                         reinitLyXText();
2172                 } else if (do_resize) {
2173                         resizeLyXText(do_resize);
2174                 } else {
2175                         if (lt || !it->second.remove) {
2176                                 lyx::Assert(it->second.text.get());
2177                                 cached_text = it->second.text;
2178                                 if (recursive && the_locking_inset) {
2179                                         return the_locking_inset->getLyXText(bv, true);
2180                                 }
2181                                 return cached_text.get();
2182                         } else if (it->second.remove) {
2183                                 if (locked) {
2184                                         saveLyXTextState(it->second.text.get());
2185                                 } else {
2186                                         sstate.lpar = 0;
2187                                 }
2188                         }
2189                         //
2190                         // when we have to reinit the existing LyXText!
2191                         //
2192                         it->second.text->init(bv);
2193                         restoreLyXTextState(it->second.text.get());
2194                         it->second.remove = false;
2195                 }
2196                 cached_text = it->second.text;
2197                 if (the_locking_inset && recursive) {
2198                         return the_locking_inset->getLyXText(bv);
2199                 }
2200                 return cached_text.get();
2201         }
2202         ///
2203         // we are here only if we don't have a BufferView * in the cache!!!
2204         ///
2205         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2206         cached_text->init(bv);
2207         restoreLyXTextState(cached_text.get());
2208
2209         cache.insert(make_pair(bv, cached_text));
2210
2211         if (the_locking_inset && recursive) {
2212                 return the_locking_inset->getLyXText(bv);
2213         }
2214         return cached_text.get();
2215 }
2216
2217
2218 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2219 {
2220         cached_bview = 0;
2221
2222         Cache::iterator it = cache.find(bv);
2223
2224         if (it == cache.end()) {
2225                 return;
2226         }
2227
2228         lyx::Assert(it->second.text.get());
2229
2230         it->second.remove = true;
2231         if (recursive) {
2232                 /// then remove all LyXText in text-insets
2233                 for_each(paragraphs.begin(), paragraphs.end(),
2234                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2235         }
2236 }
2237
2238
2239 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2240 {
2241         if (lt) {
2242                 // we cannot resize this because we are in use!
2243                 // so do this on the next possible getLyXText()
2244                 do_resize = bv;
2245                 return;
2246         }
2247         do_resize = 0;
2248         if (!paragraphs.begin()->next() && paragraphs.begin()->empty()) { // no data, resize not neccessary!
2249                 // we have to do this as a fixed width may have changed!
2250                 LyXText * t = getLyXText(bv);
2251                 saveLyXTextState(t);
2252                 t->init(bv, true);
2253                 restoreLyXTextState(t);
2254                 return;
2255         }
2256         // one endless line, resize normally not necessary
2257         if (!force && getMaxWidth(bv, this) < 0)
2258                 return;
2259
2260         Cache::iterator it = cache.find(bv);
2261         if (it == cache.end()) {
2262                 return;
2263         }
2264         lyx::Assert(it->second.text.get());
2265
2266         LyXText * t = it->second.text.get();
2267         saveLyXTextState(t);
2268
2269         for_each(paragraphs.begin(), paragraphs.end(),
2270                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2271
2272         t->init(bv, true);
2273         restoreLyXTextState(t);
2274         if (the_locking_inset) {
2275                 inset_x = cix(bv) - top_x + drawTextXOffset;
2276                 inset_y = ciy(bv) + drawTextYOffset;
2277         }
2278
2279         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2280         if (!owner()) {
2281                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2282                 // this will scroll the screen such that the cursor becomes visible
2283                 bv->updateScrollbar();
2284         } else {
2285                 need_update |= FULL;
2286         }
2287 }
2288
2289
2290 void InsetText::reinitLyXText() const
2291 {
2292         if (lt) {
2293                 // we cannot resize this because we are in use!
2294                 // so do this on the next possible getLyXText()
2295                 do_reinit = true;
2296                 return;
2297         }
2298         do_reinit = false;
2299         do_resize = 0;
2300         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2301                 lyx::Assert(it->second.text.get());
2302
2303                 LyXText * t = it->second.text.get();
2304                 BufferView * bv = it->first;
2305
2306                 saveLyXTextState(t);
2307
2308                 for_each(paragraphs.begin(), paragraphs.end(),
2309                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2310
2311                 t->init(bv, true);
2312                 restoreLyXTextState(t);
2313                 if (the_locking_inset) {
2314                         inset_x = cix(bv) - top_x + drawTextXOffset;
2315                         inset_y = ciy(bv) + drawTextYOffset;
2316                 }
2317                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2318                 if (!owner()) {
2319                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2320                         // this will scroll the screen such that the cursor becomes visible
2321                         bv->updateScrollbar();
2322                 } else {
2323                         need_update = FULL;
2324                 }
2325         }
2326 }
2327
2328
2329 void InsetText::removeNewlines()
2330 {
2331         bool changed = false;
2332
2333         ParagraphList::iterator it = paragraphs.begin();
2334         ParagraphList::iterator end = paragraphs.end();
2335         for (; it != end; ++it) {
2336                 for (int i = 0; i < it->size(); ++i) {
2337                         if (it->isNewline(i)) {
2338                                 changed = true;
2339                                 it->erase(i);
2340                         }
2341                 }
2342         }
2343         if (changed)
2344                 reinitLyXText();
2345 }
2346
2347
2348 bool InsetText::nodraw() const
2349 {
2350         if (the_locking_inset)
2351                 return the_locking_inset->nodraw();
2352         return UpdatableInset::nodraw();
2353 }
2354
2355
2356 int InsetText::scroll(bool recursive) const
2357 {
2358         int sx = UpdatableInset::scroll(false);
2359
2360         if (recursive && the_locking_inset)
2361                 sx += the_locking_inset->scroll(recursive);
2362
2363         return sx;
2364 }
2365
2366
2367 void InsetText::selectAll(BufferView * bv)
2368 {
2369         getLyXText(bv)->cursorTop();
2370         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2371         getLyXText(bv)->cursorBottom();
2372         getLyXText(bv)->setSelection();
2373 }
2374
2375
2376 void InsetText::clearSelection(BufferView * bv)
2377 {
2378         getLyXText(bv)->clearSelection();
2379 }
2380
2381
2382 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2383 {
2384         Painter & pain = bv->painter();
2385         int w = insetWidth;
2386         int h = insetAscent + insetDescent;
2387         int ty = baseline - insetAscent;
2388
2389         if (ty < 0) {
2390                 h += ty;
2391                 ty = 0;
2392         }
2393         if ((ty + h) > pain.paperHeight())
2394                 h = pain.paperHeight();
2395         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2396                 w = pain.paperWidth();
2397         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2398         need_update = FULL;
2399 }
2400
2401
2402 Paragraph * InsetText::firstParagraph() const
2403 {
2404         Paragraph * result;
2405         if (the_locking_inset)
2406                 if ((result = the_locking_inset->firstParagraph()))
2407                         return result;
2408         return &*(paragraphs.begin());
2409 }
2410
2411
2412 Paragraph * InsetText::getFirstParagraph(int i) const
2413 {
2414         return (i == 0) ? &*(paragraphs.begin()) : 0;
2415 }
2416
2417
2418 LyXCursor const & InsetText::cursor(BufferView * bv) const
2419 {
2420         if (the_locking_inset)
2421                 return the_locking_inset->cursor(bv);
2422         return getLyXText(bv)->cursor;
2423 }
2424
2425
2426 Paragraph * InsetText::paragraph() const
2427 {
2428         return &*(paragraphs.begin());
2429 }
2430
2431
2432 void InsetText::paragraph(Paragraph * p)
2433 {
2434         // GENERAL COMMENT: We don't have to free the old paragraphs as the
2435         // caller of this function has to take care of it. This IS important
2436         // as we could have to insert a paragraph before this one and just
2437         // link the actual to a new ones next and set it with this function
2438         // and are done!
2439         paragraphs.set(p);
2440         // set ourself as owner for all the paragraphs inserted!
2441         for_each(paragraphs.begin(), paragraphs.end(),
2442                  boost::bind(&Paragraph::setInsetOwner, _1, this));
2443
2444         reinitLyXText();
2445         // redraw myself when asked for
2446         need_update = INIT;
2447 }
2448
2449
2450 Inset * InsetText::getInsetFromID(int id_arg) const
2451 {
2452         if (id_arg == id())
2453                 return const_cast<InsetText *>(this);
2454
2455         ParagraphList::iterator pit = paragraphs.begin();
2456         ParagraphList::iterator pend = paragraphs.end();
2457         for (; pit != pend; ++pit) {
2458                 InsetList::iterator it = pit->insetlist.begin();
2459                 InsetList::iterator end = pit->insetlist.end();
2460                 for (; it != end; ++it) {
2461                         if (it.getInset()->id() == id_arg)
2462                                 return it.getInset();
2463                         Inset * in = it.getInset()->getInsetFromID(id_arg);
2464                         if (in)
2465                                 return in;
2466                 }
2467         }
2468         return 0;
2469 }
2470
2471
2472 WordLangTuple const
2473 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2474                                       float & value) const
2475 {
2476         bool clear = false;
2477         WordLangTuple word;
2478
2479         if (!lt) {
2480                 lt = getLyXText(bv);
2481                 clear = true;
2482         }
2483         if (the_locking_inset) {
2484                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2485                 if (!word.word().empty()) {
2486                         value += cy(bv);
2487                         if (clear)
2488                                 lt = 0;
2489                         return word;
2490                 }
2491                 // we have to go on checking so move cursor to the next char
2492                 lt->cursor.pos(lt->cursor.pos() + 1);
2493         }
2494         word = lt->selectNextWordToSpellcheck(value);
2495         if (word.word().empty())
2496                 bv->unlockInset(const_cast<InsetText *>(this));
2497         else
2498                 value = cy(bv);
2499         if (clear)
2500                 lt = 0;
2501         return word;
2502 }
2503
2504
2505 void InsetText::selectSelectedWord(BufferView * bv)
2506 {
2507         if (the_locking_inset) {
2508                 the_locking_inset->selectSelectedWord(bv);
2509                 return;
2510         }
2511         getLyXText(bv)->selectSelectedWord();
2512         updateLocal(bv, SELECTION, false);
2513 }
2514
2515
2516 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2517 {
2518         if (the_locking_inset) {
2519                 the_locking_inset->toggleSelection(bv, kill_selection);
2520         }
2521         bool clear = false;
2522         if (!lt) {
2523                 lt = getLyXText(bv);
2524                 clear = true;
2525         }
2526
2527         int x = top_x + TEXT_TO_INSET_OFFSET;
2528
2529         RowList::iterator rowit = lt->rows().begin();
2530         RowList::iterator end = lt->rows().end();
2531         int y_offset = top_baseline - rowit->ascent_of_text();
2532         int y = y_offset;
2533         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2534                 y += rowit->height();
2535                 ++rowit;
2536         }
2537         if (y_offset < 0)
2538                 y_offset = y;
2539
2540         if (need_update & SELECTION)
2541                 need_update = NONE;
2542         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2543         if (clear)
2544                 lt = 0;
2545 }
2546
2547
2548 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2549 {
2550         bool clear = false;
2551         if (!lt) {
2552                 lt = getLyXText(bv);
2553                 clear = true;
2554         }
2555         if (the_locking_inset) {
2556                 if (the_locking_inset->nextChange(bv, length))
2557                         return true;
2558                 lt->cursorRight(true);
2559         }
2560         lyxfind::SearchResult result =
2561                 lyxfind::findNextChange(bv, lt, length);
2562
2563         if (result == lyxfind::SR_FOUND) {
2564                 LyXCursor cur = lt->cursor;
2565                 bv->unlockInset(bv->theLockingInset());
2566                 if (bv->lockInset(this))
2567                         locked = true;
2568                 lt->cursor = cur;
2569                 lt->setSelectionRange(length);
2570                 updateLocal(bv, SELECTION, false);
2571         }
2572         if (clear)
2573                 lt = 0;
2574         return result != lyxfind::SR_NOT_FOUND;
2575 }
2576
2577
2578 bool InsetText::searchForward(BufferView * bv, string const & str,
2579                               bool cs, bool mw)
2580 {
2581         bool clear = false;
2582         if (!lt) {
2583                 lt = getLyXText(bv);
2584                 clear = true;
2585         }
2586         if (the_locking_inset) {
2587                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2588                         return true;
2589                 lt->cursorRight(true);
2590         }
2591         lyxfind::SearchResult result =
2592                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2593
2594         if (result == lyxfind::SR_FOUND) {
2595                 LyXCursor cur = lt->cursor;
2596                 bv->unlockInset(bv->theLockingInset());
2597                 if (bv->lockInset(this))
2598                         locked = true;
2599                 lt->cursor = cur;
2600                 lt->setSelectionRange(str.length());
2601                 updateLocal(bv, SELECTION, false);
2602         }
2603         if (clear)
2604                 lt = 0;
2605         return (result != lyxfind::SR_NOT_FOUND);
2606 }
2607
2608 bool InsetText::searchBackward(BufferView * bv, string const & str,
2609                                bool cs, bool mw)
2610 {
2611         if (the_locking_inset) {
2612                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2613                         return true;
2614         }
2615         bool clear = false;
2616         if (!lt) {
2617                 lt = getLyXText(bv);
2618                 clear = true;
2619         }
2620         if (!locked) {
2621                 Paragraph * p = &*(paragraphs.begin());
2622                 while (p->next())
2623                         p = p->next();
2624                 lt->setCursor(p, p->size());
2625         }
2626         lyxfind::SearchResult result =
2627                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2628
2629         if (result == lyxfind::SR_FOUND) {
2630                 LyXCursor cur = lt->cursor;
2631                 bv->unlockInset(bv->theLockingInset());
2632                 if (bv->lockInset(this))
2633                         locked = true;
2634                 lt->cursor = cur;
2635                 lt->setSelectionRange(str.length());
2636                 updateLocal(bv, SELECTION, false);
2637         }
2638         if (clear)
2639                 lt = 0;
2640         return (result != lyxfind::SR_NOT_FOUND);
2641 }
2642
2643
2644 bool InsetText::checkInsertChar(LyXFont & font)
2645 {
2646         if (owner())
2647                 return owner()->checkInsertChar(font);
2648         return true;
2649 }
2650
2651
2652 void InsetText::collapseParagraphs(BufferView * bv)
2653 {
2654         LyXText * llt = getLyXText(bv);
2655
2656         while (paragraphs.begin()->next()) {
2657                 if (!paragraphs.begin()->empty() && !paragraphs.begin()->next()->empty() &&
2658                         !paragraphs.begin()->isSeparator(paragraphs.begin()->size() - 1))
2659                 {
2660                         paragraphs.begin()->insertChar(paragraphs.begin()->size(), ' ');
2661                 }
2662                 if (llt->selection.set()) {
2663                         if (llt->selection.start.par() == paragraphs.begin()->next()) {
2664                                 llt->selection.start.par(&*(paragraphs.begin()));
2665                                 llt->selection.start.pos(
2666                                         llt->selection.start.pos() + paragraphs.begin()->size());
2667                         }
2668                         if (llt->selection.end.par() == paragraphs.begin()->next()) {
2669                                 llt->selection.end.par(&*(paragraphs.begin()));
2670                                 llt->selection.end.pos(
2671                                         llt->selection.end.pos() + paragraphs.begin()->size());
2672                         }
2673                 }
2674                 mergeParagraph(bv->buffer()->params, paragraphs, paragraphs.begin());
2675         }
2676         reinitLyXText();
2677 }
2678
2679
2680 void InsetText::getDrawFont(LyXFont & font) const
2681 {
2682         if (!owner())
2683                 return;
2684         owner()->getDrawFont(font);
2685 }
2686
2687
2688 void InsetText::appendParagraphs(Buffer * buffer,
2689                                  Paragraph * newpar)
2690 {
2691         BufferParams const & bparams = buffer->params;
2692         Paragraph * buf;
2693         Paragraph * tmpbuf = newpar;
2694         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2695         if (bparams.tracking_changes)
2696                 buf->cleanChanges();
2697
2698         while (tmpbuf->next()) {
2699                 tmpbuf = tmpbuf->next();
2700                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2701                 lastbuffer->next()->previous(lastbuffer);
2702                 lastbuffer = lastbuffer->next();
2703                 if (bparams.tracking_changes)
2704                         lastbuffer->cleanChanges();
2705         }
2706         lastbuffer = &*(paragraphs.begin());
2707         while (lastbuffer->next())
2708                 lastbuffer = lastbuffer->next();
2709         if (!newpar->empty() && !lastbuffer->empty() &&
2710                 !lastbuffer->isSeparator(lastbuffer->size() - 1))
2711         {
2712                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2713         }
2714
2715         // make the buf exactly the same layout than our last paragraph
2716         buf->makeSameLayout(lastbuffer);
2717
2718         // paste it!
2719         lastbuffer->next(buf);
2720         buf->previous(lastbuffer);
2721         mergeParagraph(buffer->params, paragraphs, lastbuffer);
2722
2723         reinitLyXText();
2724 }
2725
2726
2727 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2728 {
2729         Paragraph * par = getFirstParagraph(0);
2730         while (par) {
2731                 InsetList::iterator it  = par->insetlist.begin();
2732                 InsetList::iterator end = par->insetlist.end();
2733                 for (; it != end; ++it) {
2734                         it.getInset()->addPreview(loader);
2735                 }
2736
2737                 par = par->next();
2738         }
2739 }