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