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