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