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