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