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