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