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