]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
Remove a couple of #includes from buffer.h
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14 #include "insetnewline.h"
15
16 #include "buffer.h"
17 #include "BufferView.h"
18 #include "CutAndPaste.h"
19 #include "debug.h"
20 #include "errorlist.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "intl.h"
24 #include "lyxfind.h"
25 #include "lyxlex.h"
26 #include "lyxrc.h"
27 #include "metricsinfo.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphParameters.h"
31 #include "rowpainter.h"
32 #include "sgml.h"
33 #include "undo_funcs.h"
34 #include "WordLangTuple.h"
35
36 #include "frontends/Alert.h"
37 #include "frontends/font_metrics.h"
38 #include "frontends/LyXView.h"
39 #include "frontends/Painter.h"
40
41 #include "support/lyxalgo.h" // lyx::count
42
43 #include <boost/bind.hpp>
44
45 using std::endl;
46 using std::for_each;
47 using std::min;
48 using std::max;
49 using std::make_pair;
50 using std::auto_ptr;
51 using std::ostream;
52 using std::ifstream;
53 using std::pair;
54 using std::vector;
55
56 using namespace lyx::support;
57 using namespace lyx::graphics;
58 using namespace bv_funcs;
59
60 using lyx::pos_type;
61 using lyx::textclass_type;
62
63
64 InsetText::InsetText(BufferParams const & bp)
65         : UpdatableInset(), text_(0, this, true, paragraphs)
66 {
67         paragraphs.push_back(Paragraph());
68         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
69         if (bp.tracking_changes)
70                 paragraphs.begin()->trackChanges();
71         init(0);
72 }
73
74
75 InsetText::InsetText(InsetText const & in)
76         : UpdatableInset(in), text_(0, this, true, paragraphs)
77 {
78         init(&in);
79 }
80
81
82 InsetText & InsetText::operator=(InsetText const & it)
83 {
84         init(&it);
85         return *this;
86 }
87
88
89 void InsetText::init(InsetText const * ins)
90 {
91         if (ins) {
92                 textwidth_ = ins->textwidth_;
93                 text_.bv_owner = ins->text_.bv_owner;
94
95                 paragraphs = ins->paragraphs;
96
97                 ParagraphList::iterator pit = paragraphs.begin();
98                 ParagraphList::iterator end = paragraphs.end();
99                 for (; pit != end; ++pit)
100                         pit->setInsetOwner(this);
101
102                 autoBreakRows = ins->autoBreakRows;
103                 drawFrame_ = ins->drawFrame_;
104                 frame_color = ins->frame_color;
105         } else {
106                 textwidth_ = 0; // broken
107                 drawFrame_ = NEVER;
108                 frame_color = LColor::insetframe;
109                 autoBreakRows = false;
110         }
111         the_locking_inset = 0;
112         for_each(paragraphs.begin(), paragraphs.end(),
113                  boost::bind(&Paragraph::setInsetOwner, _1, this));
114         top_y = 0;
115         no_selection = true;
116         drawTextXOffset = 0;
117         drawTextYOffset = 0;
118         locked = false;
119         old_par = paragraphs.end();
120         in_insetAllowed = false;
121 }
122
123
124 void InsetText::clear(bool just_mark_erased)
125 {
126         if (just_mark_erased) {
127                 ParagraphList::iterator it = paragraphs.begin();
128                 ParagraphList::iterator end = paragraphs.end();
129                 for (; it != end; ++it)
130                         it->markErased();
131                 return;
132         }
133
134         // This is a gross hack...
135         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
136
137         paragraphs.clear();
138         paragraphs.push_back(Paragraph());
139         paragraphs.begin()->setInsetOwner(this);
140         paragraphs.begin()->layout(old_layout);
141 }
142
143
144 auto_ptr<InsetBase> InsetText::clone() const
145 {
146         return auto_ptr<InsetBase>(new InsetText(*this));
147 }
148
149
150 void InsetText::write(Buffer const & buf, ostream & os) const
151 {
152         os << "Text\n";
153         writeParagraphData(buf, os);
154 }
155
156
157 void InsetText::writeParagraphData(Buffer const & buf, ostream & os) const
158 {
159         ParagraphList::const_iterator it = paragraphs.begin();
160         ParagraphList::const_iterator end = paragraphs.end();
161         Paragraph::depth_type dth = 0;
162         for (; it != end; ++it) {
163                 it->write(buf, os, buf.params, dth);
164         }
165 }
166
167
168 void InsetText::read(Buffer const & buf, LyXLex & lex)
169 {
170         string token;
171         Paragraph::depth_type depth = 0;
172
173         clear(false);
174
175         if (buf.params.tracking_changes)
176                 paragraphs.begin()->trackChanges();
177
178         // delete the initial paragraph
179         paragraphs.clear();
180         ParagraphList::iterator pit = paragraphs.begin();
181
182         while (lex.isOK()) {
183                 lex.nextToken();
184                 token = lex.getString();
185                 if (token.empty())
186                         continue;
187                 if (token == "\\end_inset") {
188                         break;
189                 }
190
191                 if (token == "\\end_document") {
192                         lex.printError("\\end_document read in inset! Error in document!");
193                         return;
194                 }
195
196                 // FIXME: ugly.
197                 const_cast<Buffer&>(buf).readParagraph(lex, token, paragraphs, pit, depth);
198         }
199
200         pit = paragraphs.begin();
201         ParagraphList::iterator const end = paragraphs.end();
202         for (; pit != end; ++pit)
203                 pit->setInsetOwner(this);
204
205         if (token != "\\end_inset") {
206                 lex.printError("Missing \\end_inset at this point. "
207                                            "Read: `$$Token'");
208         }
209 }
210
211
212 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
213 {
214         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
215
216         textwidth_ = mi.base.textwidth;
217         BufferView * bv = mi.base.bv;
218         setViewCache(bv);
219         text_.metrics(mi, dim);
220         dim.asc += TEXT_TO_INSET_OFFSET;
221         dim.des += TEXT_TO_INSET_OFFSET;
222         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
223         dim.wid = max(dim.wid, 10);
224         dim_ = dim;
225 }
226
227
228 int InsetText::textWidth() const
229 {
230         return textwidth_;
231 }
232
233
234 void InsetText::draw(PainterInfo & pi, int x, int y) const
235 {
236         // update our idea of where we are. Clearly, we should
237         // not have to know this information.
238         top_x = x;
239
240         int const start_x = x;
241
242         BufferView * bv = pi.base.bv;
243         Painter & pain = pi.pain;
244
245         // repaint the background if needed
246         if (backgroundColor() != LColor::background)
247                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, y);
248
249         // no draw is necessary !!!
250         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
251                 top_baseline = y;
252                 return;
253         }
254
255         bv->hideCursor();
256
257         if (!owner())
258                 x += scroll();
259
260         top_baseline = y;
261         top_y = y - dim_.asc;
262
263         if (the_locking_inset && cpar() == inset_par && cpos() == inset_pos) {
264                 inset_x = cx() - x + drawTextXOffset;
265                 inset_y = cy() + drawTextYOffset;
266         }
267
268         x += TEXT_TO_INSET_OFFSET;
269
270         paintTextInset(*bv, text_, x, y);
271
272         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
273                 drawFrame(pain, start_x);
274 }
275
276
277 void InsetText::drawFrame(Painter & pain, int x) const
278 {
279         int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
280         int const frame_x = x + ttoD2;
281         int const frame_y = top_baseline - dim_.asc + ttoD2;
282         int const frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
283         int const frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
284         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frame_color);
285 }
286
287
288 void InsetText::updateLocal(BufferView * bv, bool /*mark_dirty*/)
289 {
290         if (!bv)
291                 return;
292
293         if (!autoBreakRows && paragraphs.size() > 1)
294                 collapseParagraphs(bv);
295
296         if (!text_.selection.set())
297                 text_.selection.cursor = text_.cursor;
298
299         bv->fitCursor();
300         bv->updateInset(this);
301         bv->owner()->view_state_changed();
302         bv->owner()->updateMenubar();
303         bv->owner()->updateToolbar();
304         if (old_par != cpar()) {
305                 bv->owner()->setLayout(cpar()->layout()->name());
306                 old_par = cpar();
307         }
308 }
309
310
311 string const InsetText::editMessage() const
312 {
313         return _("Opened Text Inset");
314 }
315
316
317 void InsetText::insetUnlock(BufferView * bv)
318 {
319         if (the_locking_inset) {
320                 the_locking_inset->insetUnlock(bv);
321                 the_locking_inset = 0;
322                 updateLocal(bv, false);
323         }
324         no_selection = true;
325         locked = false;
326
327         if (text_.selection.set()) {
328                 text_.clearSelection();
329         } else if (owner()) {
330                 bv->owner()->setLayout(owner()->getLyXText(bv)
331                                        ->cursor.par()->layout()->name());
332         } else
333                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
334         // hack for deleteEmptyParMech
335         ParagraphList::iterator first_par = paragraphs.begin();
336         if (!first_par->empty()) {
337                 text_.setCursor(first_par, 0);
338         } else if (paragraphs.size() > 1) {
339                 text_.setCursor(boost::next(first_par), 0);
340         }
341 }
342
343
344 void InsetText::lockInset(BufferView * bv)
345 {
346         locked = true;
347         the_locking_inset = 0;
348         inset_pos = inset_x = inset_y = 0;
349         inset_boundary = false;
350         inset_par = paragraphs.end();
351         old_par = paragraphs.end();
352         text_.setCursorIntern(paragraphs.begin(), 0);
353         text_.clearSelection();
354         finishUndo();
355         // If the inset is empty set the language of the current font to the
356         // language to the surronding text (if different).
357         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
358                 bv->getParentLanguage(this) != text_.current_font.language()) {
359                 LyXFont font(LyXFont::ALL_IGNORE);
360                 font.setLanguage(bv->getParentLanguage(this));
361                 setFont(bv, font, false);
362         }
363 }
364
365
366 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
367 {
368         the_locking_inset = inset;
369         inset_x = cx() - top_x + drawTextXOffset;
370         inset_y = cy() + drawTextYOffset;
371         inset_pos = cpos();
372         inset_par = cpar();
373         inset_boundary = cboundary();
374 }
375
376
377 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
378 {
379         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
380                               << inset << "): " << endl;
381         if (!inset)
382                 return false;
383         if (!the_locking_inset) {
384                 ParagraphList::iterator pit = paragraphs.begin();
385                 ParagraphList::iterator pend = paragraphs.end();
386
387                 int const id = inset->id();
388                 for (; pit != pend; ++pit) {
389                         InsetList::iterator it = pit->insetlist.begin();
390                         InsetList::iterator const end = pit->insetlist.end();
391                         for (; it != end; ++it) {
392                                 if (it->inset == inset) {
393                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
394                                         text_.setCursorIntern(pit, it->pos);
395                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
396                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
397                                         lockInset(bv, inset);
398                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
399                                         return true;
400                                 }
401                                 if (it->inset->getInsetFromID(id)) {
402                                         lyxerr << "InsetText::lockInsetInInset: 2" << endl;
403                                         text_.setCursorIntern(pit, it->pos);
404                                         it->inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
405                                         return the_locking_inset->lockInsetInInset(bv, inset);
406                                 }
407                         }
408                 }
409                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
410                 return false;
411         }
412         if (inset == cpar()->getInset(cpos())) {
413                 lyxerr[Debug::INSETS] << "OK" << endl;
414                 lockInset(bv, inset);
415                 return true;
416         }
417
418         if (the_locking_inset && the_locking_inset == inset) {
419                 if (cpar() == inset_par && cpos() == inset_pos) {
420                         lyxerr[Debug::INSETS] << "OK" << endl;
421                         inset_x = cx() - top_x + drawTextXOffset;
422                         inset_y = cy() + drawTextYOffset;
423                 } else {
424                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
425                 }
426         } else if (the_locking_inset) {
427                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
428                 return the_locking_inset->lockInsetInInset(bv, inset);
429         }
430         lyxerr[Debug::INSETS] << "NOT OK" << endl;
431         return false;
432 }
433
434
435 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
436                                    bool lr)
437 {
438         if (!the_locking_inset)
439                 return false;
440         if (the_locking_inset == inset) {
441                 the_locking_inset->insetUnlock(bv);
442                 the_locking_inset = 0;
443                 if (lr)
444                         moveRightIntern(bv, true, false);
445                 old_par = paragraphs.end(); // force layout setting
446                 if (scroll())
447                         scroll(bv, 0.0F);
448                 else
449                         updateLocal(bv, false);
450                 return true;
451         }
452         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
453 }
454
455
456 void InsetText::lfunMousePress(FuncRequest const & cmd)
457 {
458         no_selection = true;
459
460         // use this to check mouse motion for selection!
461         mouse_x = cmd.x;
462         mouse_y = cmd.y;
463
464         BufferView * bv = cmd.view();
465         FuncRequest cmd1 = cmd;
466         cmd1.x -= inset_x;
467         cmd1.y -= inset_y;
468         if (!locked)
469                 lockInset(bv);
470
471         int tmp_x = cmd.x - drawTextXOffset;
472         int tmp_y = cmd.y + dim_.asc - bv->top_y();
473         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
474
475         if (the_locking_inset) {
476                 if (the_locking_inset == inset) {
477                         the_locking_inset->localDispatch(cmd1);
478                         return;
479                 }
480                 // otherwise only unlock the_locking_inset
481                 the_locking_inset->insetUnlock(bv);
482                 the_locking_inset = 0;
483         }
484         if (!inset)
485                 no_selection = false;
486
487         if (bv->theLockingInset()) {
488                 if (isHighlyEditableInset(inset)) {
489                         // We just have to lock the inset before calling a
490                         // PressEvent on it!
491                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
492                         if (!bv->lockInset(uinset)) {
493                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
494                         }
495                         inset->localDispatch(cmd1);
496                         if (the_locking_inset)
497                                 updateLocal(bv, false);
498                         return;
499                 }
500         }
501         if (!inset) {
502                 bool paste_internally = false;
503                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
504                         localDispatch(FuncRequest(bv, LFUN_COPY));
505                         paste_internally = true;
506                 }
507                 int old_top_y = bv->top_y();
508
509                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
510                                              cmd.y + dim_.asc);
511                 // set the selection cursor!
512                 text_.selection.cursor = text_.cursor;
513                 text_.cursor.x_fix(text_.cursor.x());
514
515                 text_.clearSelection();
516                 updateLocal(bv, false);
517
518                 bv->owner()->setLayout(cpar()->layout()->name());
519
520                 // we moved the view we cannot do mouse selection in this case!
521                 if (bv->top_y() != old_top_y)
522                         no_selection = true;
523                 old_par = cpar();
524                 // Insert primary selection with middle mouse
525                 // if there is a local selection in the current buffer,
526                 // insert this
527                 if (cmd.button() == mouse_button::button2) {
528                         if (paste_internally)
529                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
530                         else
531                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
532                 }
533         } else {
534                 getLyXText(bv)->clearSelection();
535         }
536 }
537
538
539 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
540 {
541         BufferView * bv = cmd.view();
542         FuncRequest cmd1 = cmd;
543         cmd1.x -= inset_x;
544         cmd1.y -= inset_y;
545
546         no_selection = true;
547         if (the_locking_inset)
548                 return the_locking_inset->localDispatch(cmd1);
549
550         int tmp_x = cmd.x - drawTextXOffset;
551         int tmp_y = cmd.y + dim_.asc - bv->top_y();
552         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
553         bool ret = false;
554         if (inset) {
555 // This code should probably be removed now. Simple insets
556 // (!highlyEditable) can actually take the localDispatch,
557 // and turn it into edit() if necessary. But we still
558 // need to deal properly with the whole relative vs.
559 // absolute mouse co-ords thing in a realiable, sensible way
560 #if 0
561                 if (isHighlyEditableInset(inset))
562                         ret = inset->localDispatch(cmd1);
563                 else {
564                         inset_x = cx(bv) - top_x + drawTextXOffset;
565                         inset_y = cy() + drawTextYOffset;
566                         cmd1.x = cmd.x - inset_x;
567                         cmd1.y = cmd.x - inset_y;
568                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
569                         ret = true;
570                 }
571 #endif
572                 ret = inset->localDispatch(cmd1);
573                 updateLocal(bv, false);
574
575         }
576         return ret;
577 }
578
579
580 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
581 {
582         FuncRequest cmd1 = cmd;
583         cmd1.x -= inset_x;
584         cmd1.y -= inset_y;
585
586         if (the_locking_inset) {
587                 the_locking_inset->localDispatch(cmd1);
588                 return;
589         }
590
591         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
592                 return;
593
594         BufferView * bv = cmd.view();
595         LyXCursor cur = text_.cursor;
596         text_.setCursorFromCoordinates
597                 (cmd.x - drawTextXOffset, cmd.y + dim_.asc);
598         text_.cursor.x_fix(text_.cursor.x());
599         if (cur == text_.cursor)
600                 return;
601         text_.setSelection();
602         updateLocal(bv, false);
603 }
604
605
606 InsetOld::RESULT InsetText::localDispatch(FuncRequest const & cmd)
607 {
608         BufferView * bv = cmd.view();
609         setViewCache(bv);
610
611         switch (cmd.action) {
612         case LFUN_INSET_EDIT: {
613                 UpdatableInset::localDispatch(cmd);
614
615                 if (!bv->lockInset(this)) {
616                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
617                         return DISPATCHED;
618                 }
619
620                 locked = true;
621                 the_locking_inset = 0;
622                 inset_pos = 0;
623                 inset_x = 0;
624                 inset_y = 0;
625                 inset_boundary = false;
626                 inset_par = paragraphs.end();
627                 old_par = paragraphs.end();
628
629
630                 if (cmd.argument.size()) {
631                         if (cmd.argument == "left")
632                                 text_.setCursorIntern(paragraphs.begin(), 0);
633                         else {
634                                 ParagraphList::iterator it = boost::prior(paragraphs.end());
635                                 text_.setCursor(it, it->size());
636                         }
637                 } else {
638                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
639                         // we put here -1 and not button as now the button in the
640                         // edit call should not be needed we will fix this in 1.3.x
641                         // cycle hopefully (Jug 20020509)
642                         // FIXME: GUII I've changed this to none: probably WRONG
643                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
644                                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
645                                                                         cmd.y + dim_.asc);
646                                 text_.cursor.x(text_.cursor.x());
647                                 text_.cursor.x_fix(text_.cursor.x());
648                         }
649                 }
650
651                 text_.clearSelection();
652                 finishUndo();
653
654                 // If the inset is empty set the language of the current font to the
655                 // language to the surronding text (if different).
656                 if (paragraphs.begin()->empty() &&
657                     paragraphs.size() == 1 &&
658                     bv->getParentLanguage(this) != text_.current_font.language())
659                 {
660                         LyXFont font(LyXFont::ALL_IGNORE);
661                         font.setLanguage(bv->getParentLanguage(this));
662                         setFont(bv, font, false);
663                 }
664
665                 updateLocal(bv, false);
666                 // Tell the paragraph dialog that we've entered an insettext.
667                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
668                 return DISPATCHED;
669         }
670
671         case LFUN_MOUSE_PRESS:
672                 lfunMousePress(cmd);
673                 return DISPATCHED;
674
675         case LFUN_MOUSE_MOTION:
676                 lfunMouseMotion(cmd);
677                 return DISPATCHED;
678
679         case LFUN_MOUSE_RELEASE:
680                 return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
681
682         default:
683                 break;
684         }
685
686         bool was_empty = paragraphs.begin()->empty() && paragraphs.size() == 1;
687         no_selection = false;
688
689         RESULT result = UpdatableInset::localDispatch(cmd);
690         if (result != UNDISPATCHED)
691                 return DISPATCHED;
692
693         result = DISPATCHED;
694         if (cmd.action < 0 && cmd.argument.empty())
695                 return FINISHED;
696
697         if (the_locking_inset) {
698                 result = the_locking_inset->localDispatch(cmd);
699                 if (result == DISPATCHED_NOUPDATE)
700                         return result;
701                 if (result == DISPATCHED) {
702                         updateLocal(bv, false);
703                         return result;
704                 }
705                 if (result >= FINISHED) {
706                         switch (result) {
707                         case FINISHED_RIGHT:
708                                 moveRightIntern(bv, false, false);
709                                 result = DISPATCHED;
710                                 break;
711                         case FINISHED_UP:
712                                 result = moveUp(bv);
713                                 if (result >= FINISHED) {
714                                         updateLocal(bv, false);
715                                         bv->unlockInset(this);
716                                 }
717                                 break;
718                         case FINISHED_DOWN:
719                                 result = moveDown(bv);
720                                 if (result >= FINISHED) {
721                                         updateLocal(bv, false);
722                                         bv->unlockInset(this);
723                                 }
724                                 break;
725                         default:
726                                 result = DISPATCHED;
727                                 break;
728                         }
729                         the_locking_inset = 0;
730                         updateLocal(bv, false);
731                         // make sure status gets reset immediately
732                         bv->owner()->clearMessage();
733                         return result;
734                 }
735         }
736         bool updflag = false;
737
738         switch (cmd.action) {
739
740         // Normal chars
741         case LFUN_SELFINSERT:
742                 if (bv->buffer()->isReadonly()) {
743 //          setErrorMessage(N_("Document is read only"));
744                         break;
745                 }
746                 if (!cmd.argument.empty()) {
747                         /* Automatically delete the currently selected
748                          * text and replace it with what is being
749                          * typed in now. Depends on lyxrc settings
750                          * "auto_region_delete", which defaults to
751                          * true (on). */
752 #if 0
753                         // This should not be needed here and is also WRONG!
754                         recordUndo(bv, Undo::INSERT, text_.cursor.par());
755 #endif
756                         bv->switchKeyMap();
757
758                         if (lyxrc.auto_region_delete && text_.selection.set())
759                                 text_.cutSelection(false, false);
760                         text_.clearSelection();
761
762                         for (string::size_type i = 0; i < cmd.argument.length(); ++i)
763                                 bv->owner()->getIntl().getTransManager().
764                                         TranslateAndInsert(cmd.argument[i], &text_);
765                 }
766                 text_.selection.cursor = text_.cursor;
767                 updflag = true;
768                 result = DISPATCHED_NOUPDATE;
769                 break;
770
771         // cursor movements that need special handling
772
773         case LFUN_RIGHT:
774                 result = moveRight(bv);
775                 finishUndo();
776                 break;
777         case LFUN_LEFT:
778                 finishUndo();
779                 result = moveLeft(bv);
780                 break;
781         case LFUN_DOWN:
782                 finishUndo();
783                 result = moveDown(bv);
784                 break;
785         case LFUN_UP:
786                 finishUndo();
787                 result = moveUp(bv);
788                 break;
789
790         case LFUN_PRIOR:
791                 if (crow() == text_.firstRow())
792                         result = FINISHED_UP;
793                 else {
794                         text_.cursorPrevious();
795                         text_.clearSelection();
796                         result = DISPATCHED_NOUPDATE;
797                 }
798                 break;
799
800         case LFUN_NEXT:
801                 if (crow() == text_.lastRow())
802                         result = FINISHED_DOWN;
803                 else {
804                         text_.cursorNext();
805                         text_.clearSelection();
806                         result = DISPATCHED_NOUPDATE;
807                 }
808                 break;
809
810         case LFUN_BACKSPACE:
811                 if (text_.selection.set())
812                         text_.cutSelection(true, false);
813                 else
814                         text_.backspace();
815                 updflag = true;
816                 break;
817
818         case LFUN_DELETE:
819                 if (text_.selection.set())
820                         text_.cutSelection(true, false);
821                 else
822                         text_.Delete();
823                 updflag = true;
824                 break;
825
826         case LFUN_PASTE: {
827                 if (!autoBreakRows) {
828                         if (CutAndPaste::nrOfParagraphs() > 1) {
829 #ifdef WITH_WARNINGS
830 #warning FIXME horrendously bad UI
831 #endif
832                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
833                                 break;
834                         }
835                 }
836
837                 replaceSelection(bv->getLyXText());
838                 size_t sel_index = 0;
839                 string const & arg = cmd.argument;
840                 if (isStrUnsignedInt(arg)) {
841                         size_t const paste_arg = strToUnsignedInt(arg);
842 #warning FIXME Check if the arg is in the domain of available selections.
843                         sel_index = paste_arg;
844                 }
845                 text_.pasteSelection(sel_index);
846                 // bug 393
847                 text_.clearSelection();
848                 updflag = true;
849                 break;
850         }
851
852         case LFUN_BREAKPARAGRAPH:
853                 if (!autoBreakRows) {
854                         result = DISPATCHED;
855                         break;
856                 }
857                 replaceSelection(bv->getLyXText());
858                 text_.breakParagraph(paragraphs, 0);
859                 updflag = true;
860                 break;
861
862         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
863                 if (!autoBreakRows) {
864                         result = DISPATCHED;
865                         break;
866                 }
867                 replaceSelection(bv->getLyXText());
868                 text_.breakParagraph(paragraphs, 1);
869                 updflag = true;
870                 break;
871
872         case LFUN_BREAKLINE: {
873                 if (!autoBreakRows) {
874                         result = DISPATCHED;
875                         break;
876                 }
877
878                 replaceSelection(bv->getLyXText());
879                 text_.insertInset(new InsetNewline);
880                 updflag = true;
881                 break;
882         }
883
884         case LFUN_LAYOUT:
885                 // do not set layouts on non breakable textinsets
886                 if (autoBreakRows) {
887                         string cur_layout = cpar()->layout()->name();
888
889                         // Derive layout number from given argument (string)
890                         // and current buffer's textclass (number).
891                         LyXTextClass const & tclass =
892                                 bv->buffer()->params.getLyXTextClass();
893                         string layout = cmd.argument;
894                         bool hasLayout = tclass.hasLayout(layout);
895
896                         // If the entry is obsolete, use the new one instead.
897                         if (hasLayout) {
898                                 string const & obs = tclass[layout]->obsoleted_by();
899                                 if (!obs.empty())
900                                         layout = obs;
901                         }
902
903                         // see if we found the layout number:
904                         if (!hasLayout) {
905                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
906                                 bv->owner()->dispatch(lf);
907                                 break;
908                         }
909
910                         if (cur_layout != layout) {
911                                 cur_layout = layout;
912                                 text_.setLayout(layout);
913                                 bv->owner()->setLayout(cpar()->layout()->name());
914                                 updflag = true;
915                         }
916                 } else {
917                         // reset the layout box
918                         bv->owner()->setLayout(cpar()->layout()->name());
919                 }
920                 break;
921
922         default:
923                 if (!bv->dispatch(cmd))
924                         result = UNDISPATCHED;
925                 break;
926         }
927
928         updateLocal(bv, updflag);
929
930         /// If the action has deleted all text in the inset, we need to change the
931         // language to the language of the surronding text.
932         if (!was_empty && paragraphs.begin()->empty() &&
933             paragraphs.size() == 1) {
934                 LyXFont font(LyXFont::ALL_IGNORE);
935                 font.setLanguage(bv->getParentLanguage(this));
936                 setFont(bv, font, false);
937         }
938
939         if (result >= FINISHED)
940                 bv->unlockInset(this);
941
942         if (result == DISPATCHED_NOUPDATE)
943                 result = DISPATCHED;
944         return result;
945 }
946
947
948 int InsetText::latex(Buffer const & buf, ostream & os,
949                      LatexRunParams const & runparams) const
950 {
951         TexRow texrow;
952         latexParagraphs(buf, paragraphs, os, texrow, runparams);
953         return texrow.rows();
954 }
955
956
957 int InsetText::ascii(Buffer const & buf, ostream & os, int linelen) const
958 {
959         unsigned int lines = 0;
960
961         ParagraphList::const_iterator beg = paragraphs.begin();
962         ParagraphList::const_iterator end = paragraphs.end();
963         ParagraphList::const_iterator it = beg;
964         for (; it != end; ++it) {
965                 string const tmp = buf.asciiParagraph(*it, linelen, it == beg);
966                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
967                 os << tmp;
968         }
969         return lines;
970 }
971
972
973 int InsetText::linuxdoc(Buffer const & buf, ostream & os) const
974 {
975         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
976         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
977
978         // There is a confusion between the empty paragraph and the default paragraph
979         // The default paragraph is <p></p>, the empty paragraph is *empty*
980         // Since none of the floats of linuxdoc accepts standard paragraphs
981         // I disable them. I don't expect problems. (jamatos 2003/07/27)
982         for (; pit != pend; ++pit) {
983                 const string name = pit->layout()->latexname();
984                 if (name != "p")
985                         sgml::openTag(os, 1, 0, name);
986                 buf.simpleLinuxDocOnePar(os, pit, 0);
987                 if (name != "p")
988                         sgml::closeTag(os, 1, 0, name);
989         }
990         return 0;
991 }
992
993
994 int InsetText::docbook(Buffer const & buf, ostream & os, bool mixcont) const
995 {
996         unsigned int lines = 0;
997
998         vector<string> environment_stack(10);
999         vector<string> environment_inner(10);
1000
1001         int const command_depth = 0;
1002         string item_name;
1003
1004         Paragraph::depth_type depth = 0; // paragraph depth
1005
1006         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1007         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1008
1009         for (; pit != pend; ++pit) {
1010                 int desc_on = 0; // description mode
1011
1012                 LyXLayout_ptr const & style = pit->layout();
1013
1014                 // environment tag closing
1015                 for (; depth > pit->params().depth(); --depth) {
1016                         if (environment_inner[depth] != "!-- --") {
1017                                 item_name = "listitem";
1018                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1019                                 if (environment_inner[depth] == "varlistentry")
1020                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1021                         }
1022                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1023                         environment_stack[depth].erase();
1024                         environment_inner[depth].erase();
1025                 }
1026
1027                 if (depth == pit->params().depth()
1028                    && environment_stack[depth] != style->latexname()
1029                    && !environment_stack[depth].empty()) {
1030                         if (environment_inner[depth] != "!-- --") {
1031                                 item_name= "listitem";
1032                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1033                                 if (environment_inner[depth] == "varlistentry")
1034                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1035                         }
1036
1037                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1038
1039                         environment_stack[depth].erase();
1040                         environment_inner[depth].erase();
1041                 }
1042
1043                 // Write opening SGML tags.
1044                 switch (style->latextype) {
1045                 case LATEX_PARAGRAPH:
1046                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1047                         break;
1048
1049                 case LATEX_COMMAND:
1050                         buf.error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1051                         return -1;
1052                         break;
1053
1054                 case LATEX_ENVIRONMENT:
1055                 case LATEX_ITEM_ENVIRONMENT:
1056                         if (depth < pit->params().depth()) {
1057                                 depth = pit->params().depth();
1058                                 environment_stack[depth].erase();
1059                         }
1060
1061                         if (environment_stack[depth] != style->latexname()) {
1062                                 if (environment_stack.size() == depth + 1) {
1063                                         environment_stack.push_back("!-- --");
1064                                         environment_inner.push_back("!-- --");
1065                                 }
1066                                 environment_stack[depth] = style->latexname();
1067                                 environment_inner[depth] = "!-- --";
1068                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1069                         } else {
1070                                 if (environment_inner[depth] != "!-- --") {
1071                                         item_name= "listitem";
1072                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1073                                         if (environment_inner[depth] == "varlistentry")
1074                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1075                                 }
1076                         }
1077
1078                         if (style->latextype == LATEX_ENVIRONMENT) {
1079                                 if (!style->latexparam().empty()) {
1080                                         if (style->latexparam() == "CDATA")
1081                                                 os << "<![CDATA[";
1082                                         else
1083                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1084                                 }
1085                                 break;
1086                         }
1087
1088                         desc_on = (style->labeltype == LABEL_MANUAL);
1089
1090                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1091                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1092
1093                         item_name = desc_on ? "term" : "para";
1094                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1095
1096                         break;
1097                 default:
1098                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1099                         break;
1100                 }
1101
1102                 buf.simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1103
1104                 string end_tag;
1105                 // write closing SGML tags
1106                 switch (style->latextype) {
1107                 case LATEX_ENVIRONMENT:
1108                         if (!style->latexparam().empty()) {
1109                                 if (style->latexparam() == "CDATA")
1110                                         os << "]]>";
1111                                 else
1112                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1113                         }
1114                         break;
1115                 case LATEX_ITEM_ENVIRONMENT:
1116                         if (desc_on == 1)
1117                                 break;
1118                         end_tag= "para";
1119                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1120                         break;
1121                 case LATEX_PARAGRAPH:
1122                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1123                         break;
1124                 default:
1125                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1126                         break;
1127                 }
1128         }
1129
1130         // Close open tags
1131         for (int d = depth; d >= 0; --d) {
1132                 if (!environment_stack[depth].empty()) {
1133                         if (environment_inner[depth] != "!-- --") {
1134                                 item_name = "listitem";
1135                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1136                                if (environment_inner[depth] == "varlistentry")
1137                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1138                         }
1139
1140                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1141                 }
1142         }
1143
1144         return lines;
1145 }
1146
1147
1148 void InsetText::validate(LaTeXFeatures & features) const
1149 {
1150         for_each(paragraphs.begin(), paragraphs.end(),
1151                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1152 }
1153
1154
1155 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1156 {
1157         if (the_locking_inset) {
1158                 the_locking_inset->getCursor(bv, x, y);
1159                 return;
1160         }
1161         x = cx();
1162         y = cy() + InsetText::y();
1163 }
1164
1165
1166 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1167 {
1168         if (the_locking_inset) {
1169                 the_locking_inset->getCursorPos(bv, x, y);
1170                 return;
1171         }
1172         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1173         y = cy() - TEXT_TO_INSET_OFFSET;
1174 }
1175
1176
1177 int InsetText::insetInInsetY() const
1178 {
1179         if (!the_locking_inset)
1180                 return 0;
1181
1182         return inset_y + the_locking_inset->insetInInsetY();
1183 }
1184
1185
1186 void InsetText::fitInsetCursor(BufferView * bv) const
1187 {
1188         if (the_locking_inset) {
1189                 the_locking_inset->fitInsetCursor(bv);
1190                 return;
1191         }
1192
1193         LyXFont const font = text_.getFont(cpar(), cpos());
1194
1195         int const asc = font_metrics::maxAscent(font);
1196         int const desc = font_metrics::maxDescent(font);
1197
1198         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1199 }
1200
1201
1202 InsetOld::RESULT InsetText::moveRight(BufferView * bv)
1203 {
1204         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1205                 return moveLeftIntern(bv, false, true, false);
1206         else
1207                 return moveRightIntern(bv, true, true, false);
1208 }
1209
1210
1211 InsetOld::RESULT InsetText::moveLeft(BufferView * bv)
1212 {
1213         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1214                 return moveRightIntern(bv, true, true, false);
1215         else
1216                 return moveLeftIntern(bv, false, true, false);
1217 }
1218
1219
1220 InsetOld::RESULT
1221 InsetText::moveRightIntern(BufferView * bv, bool front,
1222                            bool activate_inset, bool selecting)
1223 {
1224         ParagraphList::iterator c_par = cpar();
1225
1226         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1227                 return FINISHED_RIGHT;
1228         if (activate_inset && checkAndActivateInset(bv, front))
1229                 return DISPATCHED;
1230         text_.cursorRight(bv);
1231         if (!selecting)
1232                 text_.clearSelection();
1233         return DISPATCHED_NOUPDATE;
1234 }
1235
1236
1237 InsetOld::RESULT
1238 InsetText::moveLeftIntern(BufferView * bv, bool front,
1239                           bool activate_inset, bool selecting)
1240 {
1241         if (cpar() == paragraphs.begin() && cpos() <= 0)
1242                 return FINISHED;
1243         text_.cursorLeft(bv);
1244         if (!selecting)
1245                 text_.clearSelection();
1246         if (activate_inset && checkAndActivateInset(bv, front))
1247                 return DISPATCHED;
1248         return DISPATCHED_NOUPDATE;
1249 }
1250
1251
1252 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1253 {
1254         if (crow() == text_.firstRow())
1255                 return FINISHED_UP;
1256         text_.cursorUp(bv);
1257         text_.clearSelection();
1258         return DISPATCHED_NOUPDATE;
1259 }
1260
1261
1262 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1263 {
1264         if (crow() == text_.lastRow())
1265                 return FINISHED_DOWN;
1266         text_.cursorDown(bv);
1267         text_.clearSelection();
1268         return DISPATCHED_NOUPDATE;
1269 }
1270
1271
1272 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1273 {
1274         if (the_locking_inset) {
1275                 if (the_locking_inset->insetAllowed(inset))
1276                         return the_locking_inset->insertInset(bv, inset);
1277                 return false;
1278         }
1279         inset->setOwner(this);
1280         text_.insertInset(inset);
1281         bv->fitCursor();
1282         updateLocal(bv, true);
1283         return true;
1284 }
1285
1286
1287 bool InsetText::insetAllowed(InsetOld::Code code) const
1288 {
1289         // in_insetAllowed is a really gross hack,
1290         // to allow us to call the owner's insetAllowed
1291         // without stack overflow, which can happen
1292         // when the owner uses InsetCollapsable::insetAllowed()
1293         bool ret = true;
1294         if (in_insetAllowed)
1295                 return ret;
1296         in_insetAllowed = true;
1297         if (the_locking_inset)
1298                 ret = the_locking_inset->insetAllowed(code);
1299         else if (owner())
1300                 ret = owner()->insetAllowed(code);
1301         in_insetAllowed = false;
1302         return ret;
1303 }
1304
1305
1306 UpdatableInset * InsetText::getLockingInset() const
1307 {
1308         return the_locking_inset ? the_locking_inset->getLockingInset() :
1309                 const_cast<InsetText *>(this);
1310 }
1311
1312
1313 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1314 {
1315         if (c == lyxCode())
1316                 return this;
1317         if (the_locking_inset)
1318                 return the_locking_inset->getFirstLockingInsetOfType(c);
1319         return 0;
1320 }
1321
1322
1323 bool InsetText::showInsetDialog(BufferView * bv) const
1324 {
1325         if (the_locking_inset)
1326                 return the_locking_inset->showInsetDialog(bv);
1327         return false;
1328 }
1329
1330
1331 void InsetText::getLabelList(std::vector<string> & list) const
1332 {
1333         ParagraphList::const_iterator pit = paragraphs.begin();
1334         ParagraphList::const_iterator pend = paragraphs.end();
1335         for (; pit != pend; ++pit) {
1336                 InsetList::const_iterator beg = pit->insetlist.begin();
1337                 InsetList::const_iterator end = pit->insetlist.end();
1338                 for (; beg != end; ++beg)
1339                         beg->inset->getLabelList(list);
1340         }
1341 }
1342
1343
1344 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1345                         bool selectall)
1346 {
1347         if (the_locking_inset) {
1348                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1349                 return;
1350         }
1351
1352         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1353             || cpar()->empty()) {
1354                 text_.setFont(font, toggleall);
1355                 return;
1356         }
1357
1358
1359         if (text_.selection.set())
1360                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1361
1362         if (selectall) {
1363                 text_.cursorTop();
1364                 text_.selection.cursor = text_.cursor;
1365                 text_.cursorBottom();
1366                 text_.setSelection();
1367         }
1368
1369         text_.toggleFree(font, toggleall);
1370
1371         if (selectall)
1372                 text_.clearSelection();
1373
1374         bv->fitCursor();
1375         updateLocal(bv, true);
1376 }
1377
1378
1379 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1380 {
1381         if (cpos() == cpar()->size())
1382                 return false;
1383         InsetOld * inset = cpar()->getInset(cpos());
1384         if (!isHighlyEditableInset(inset))
1385                 return false;
1386         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1387         inset->localDispatch(cmd);
1388         if (!the_locking_inset)
1389                 return false;
1390         updateLocal(bv, false);
1391         return true;
1392 }
1393
1394
1395 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1396                                       mouse_button::state button)
1397 {
1398         x -= drawTextXOffset;
1399         int dummyx = x;
1400         int dummyy = y + dim_.asc;
1401         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1402         // we only do the edit() call if the inset was hit by the mouse
1403         // or if it is a highly editable inset. So we should call this
1404         // function from our own edit with button < 0.
1405         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1406         // WRONG
1407         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1408                 return false;
1409
1410         if (!inset)
1411                 return false;
1412         if (x < 0)
1413                 x = dim_.wid;
1414         if (y < 0)
1415                 y = dim_.des;
1416         inset_x = cx() - top_x + drawTextXOffset;
1417         inset_y = cy() + drawTextYOffset;
1418         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1419         inset->localDispatch(cmd);
1420         if (!the_locking_inset)
1421                 return false;
1422         updateLocal(bv, false);
1423         return true;
1424 }
1425
1426
1427 void InsetText::markNew(bool track_changes)
1428 {
1429         ParagraphList::iterator pit = paragraphs.begin();
1430         ParagraphList::iterator end = paragraphs.end();
1431         for (; pit != end; ++pit) {
1432                 if (track_changes) {
1433                         pit->trackChanges();
1434                 } else {
1435                         // no-op when not tracking
1436                         pit->cleanChanges();
1437                 }
1438         }
1439 }
1440
1441
1442 void InsetText::setText(string const & data, LyXFont const & font)
1443 {
1444         clear(false);
1445         for (unsigned int i = 0; i < data.length(); ++i)
1446                 paragraphs.begin()->insertChar(i, data[i], font);
1447 }
1448
1449
1450 void InsetText::setAutoBreakRows(bool flag)
1451 {
1452         if (flag != autoBreakRows) {
1453                 autoBreakRows = flag;
1454                 if (!flag)
1455                         removeNewlines();
1456         }
1457 }
1458
1459
1460 void InsetText::setDrawFrame(DrawFrame how)
1461 {
1462         drawFrame_ = how;
1463 }
1464
1465
1466 void InsetText::setFrameColor(LColor::color col)
1467 {
1468         frame_color = col;
1469 }
1470
1471
1472 int InsetText::cx() const
1473 {
1474         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1475         if (the_locking_inset) {
1476                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1477                 if (font.isVisibleRightToLeft())
1478                         x -= the_locking_inset->width();
1479         }
1480         return x;
1481 }
1482
1483
1484 int InsetText::cy() const
1485 {
1486         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1487 }
1488
1489
1490 pos_type InsetText::cpos() const
1491 {
1492         return text_.cursor.pos();
1493 }
1494
1495
1496 ParagraphList::iterator InsetText::cpar() const
1497 {
1498         return text_.cursor.par();
1499 }
1500
1501
1502 bool InsetText::cboundary() const
1503 {
1504         return text_.cursor.boundary();
1505 }
1506
1507
1508 RowList::iterator InsetText::crow() const
1509 {
1510         return text_.cursorRow();
1511 }
1512
1513
1514 LyXText * InsetText::getLyXText(BufferView const * bv,
1515                                 bool const recursive) const
1516 {
1517         setViewCache(bv);
1518         if (recursive && the_locking_inset)
1519                 return the_locking_inset->getLyXText(bv, true);
1520         return &text_;
1521 }
1522
1523
1524 void InsetText::setViewCache(BufferView const * bv) const
1525 {
1526         if (bv) {
1527                 if (bv != text_.bv_owner) {
1528                         //lyxerr << "setting view cache from "
1529                         //      << text_.bv_owner << " to " << bv << "\n";
1530                         text_.init(const_cast<BufferView *>(bv));
1531                 }
1532                 text_.bv_owner = const_cast<BufferView *>(bv);
1533         }
1534 }
1535
1536
1537 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1538 {
1539         if (recursive) {
1540                 /// then remove all LyXText in text-insets
1541                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1542                          const_cast<ParagraphList&>(paragraphs).end(),
1543                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1544         }
1545 }
1546
1547
1548 void InsetText::removeNewlines()
1549 {
1550         ParagraphList::iterator it = paragraphs.begin();
1551         ParagraphList::iterator end = paragraphs.end();
1552         for (; it != end; ++it)
1553                 for (int i = 0; i < it->size(); ++i)
1554                         if (it->isNewline(i))
1555                                 it->erase(i);
1556 }
1557
1558
1559 int InsetText::scroll(bool recursive) const
1560 {
1561         int sx = UpdatableInset::scroll(false);
1562
1563         if (recursive && the_locking_inset)
1564                 sx += the_locking_inset->scroll(recursive);
1565
1566         return sx;
1567 }
1568
1569
1570 void InsetText::clearSelection(BufferView *)
1571 {
1572         text_.clearSelection();
1573 }
1574
1575
1576 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1577 {
1578         Painter & pain = bv->painter();
1579         int w = dim_.wid;
1580         int h = dim_.asc + dim_.des;
1581         int ty = baseline - dim_.asc;
1582
1583         if (ty < 0) {
1584                 h += ty;
1585                 ty = 0;
1586         }
1587         if (ty + h > pain.paperHeight())
1588                 h = pain.paperHeight();
1589         if (top_x + drawTextXOffset + w > pain.paperWidth())
1590                 w = pain.paperWidth();
1591         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1592 }
1593
1594
1595 ParagraphList * InsetText::getParagraphs(int i) const
1596 {
1597         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1598 }
1599
1600
1601 LyXCursor const & InsetText::cursor(BufferView * bv) const
1602 {
1603         if (the_locking_inset)
1604                 return the_locking_inset->cursor(bv);
1605         return getLyXText(bv)->cursor;
1606 }
1607
1608
1609 InsetOld * InsetText::getInsetFromID(int id_arg) const
1610 {
1611         if (id_arg == id())
1612                 return const_cast<InsetText *>(this);
1613
1614         ParagraphList::const_iterator pit = paragraphs.begin();
1615         ParagraphList::const_iterator pend = paragraphs.end();
1616         for (; pit != pend; ++pit) {
1617                 InsetList::const_iterator it = pit->insetlist.begin();
1618                 InsetList::const_iterator end = pit->insetlist.end();
1619                 for (; it != end; ++it) {
1620                         if (it->inset->id() == id_arg)
1621                                 return it->inset;
1622                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1623                         if (in)
1624                                 return in;
1625                 }
1626         }
1627         return 0;
1628 }
1629
1630
1631 WordLangTuple const
1632 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1633 {
1634         WordLangTuple word;
1635         if (the_locking_inset) {
1636                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1637                 if (!word.word().empty()) {
1638                         value += cy();
1639                         return word;
1640                 }
1641                 // we have to go on checking so move cursor to the next char
1642                 text_.cursor.pos(text_.cursor.pos() + 1);
1643         }
1644         word = text_.selectNextWordToSpellcheck(value);
1645         if (word.word().empty())
1646                 bv->unlockInset(const_cast<InsetText *>(this));
1647         else
1648                 value = cy();
1649         return word;
1650 }
1651
1652
1653 void InsetText::selectSelectedWord(BufferView * bv)
1654 {
1655         if (the_locking_inset) {
1656                 the_locking_inset->selectSelectedWord(bv);
1657                 return;
1658         }
1659         getLyXText(bv)->selectSelectedWord();
1660         updateLocal(bv, false);
1661 }
1662
1663
1664 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1665 {
1666         if (the_locking_inset) {
1667                 if (the_locking_inset->nextChange(bv, length))
1668                         return true;
1669                 text_.cursorRight(true);
1670         }
1671         lyx::find::SearchResult result =
1672                 lyx::find::findNextChange(bv, &text_, length);
1673
1674         if (result == lyx::find::SR_FOUND) {
1675                 LyXCursor cur = text_.cursor;
1676                 bv->unlockInset(bv->theLockingInset());
1677                 if (bv->lockInset(this))
1678                         locked = true;
1679                 text_.cursor = cur;
1680                 text_.setSelectionRange(length);
1681                 updateLocal(bv, false);
1682         }
1683         return result != lyx::find::SR_NOT_FOUND;
1684 }
1685
1686
1687 bool InsetText::searchForward(BufferView * bv, string const & str,
1688                               bool cs, bool mw)
1689 {
1690         if (the_locking_inset) {
1691                 if (the_locking_inset->searchForward(bv, str, cs, mw))
1692                         return true;
1693                 text_.cursorRight(true);
1694         }
1695         lyx::find::SearchResult result =
1696                 lyx::find::find(bv, &text_, str, true, cs, mw);
1697
1698         if (result == lyx::find::SR_FOUND) {
1699                 LyXCursor cur = text_.cursor;
1700                 bv->unlockInset(bv->theLockingInset());
1701                 if (bv->lockInset(this))
1702                         locked = true;
1703                 text_.cursor = cur;
1704                 text_.setSelectionRange(str.length());
1705                 updateLocal(bv, false);
1706         }
1707         return result != lyx::find::SR_NOT_FOUND;
1708 }
1709
1710
1711 bool InsetText::searchBackward(BufferView * bv, string const & str,
1712                                bool cs, bool mw)
1713 {
1714         if (the_locking_inset) {
1715                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
1716                         return true;
1717         }
1718         if (!locked) {
1719                 ParagraphList::iterator pit = boost::prior(paragraphs.end());
1720                 text_.setCursor(pit, pit->size());
1721         }
1722         lyx::find::SearchResult result =
1723                 lyx::find::find(bv, &text_, str, false, cs, mw);
1724
1725         if (result == lyx::find::SR_FOUND) {
1726                 LyXCursor cur = text_.cursor;
1727                 bv->unlockInset(bv->theLockingInset());
1728                 if (bv->lockInset(this))
1729                         locked = true;
1730                 text_.cursor = cur;
1731                 text_.setSelectionRange(str.length());
1732                 updateLocal(bv, false);
1733         }
1734         return result != lyx::find::SR_NOT_FOUND;
1735 }
1736
1737
1738 bool InsetText::checkInsertChar(LyXFont & font)
1739 {
1740         return owner() ? owner()->checkInsertChar(font) : true;
1741 }
1742
1743
1744 void InsetText::collapseParagraphs(BufferView * bv)
1745 {
1746         while (paragraphs.size() > 1) {
1747                 ParagraphList::iterator first_par = paragraphs.begin();
1748                 ParagraphList::iterator next_par = boost::next(first_par);
1749                 size_t const first_par_size = first_par->size();
1750
1751                 if (!first_par->empty() &&
1752                     !next_par->empty() &&
1753                     !first_par->isSeparator(first_par_size - 1)) {
1754                         first_par->insertChar(first_par_size, ' ');
1755                 }
1756
1757                 if (text_.selection.set()) {
1758                         if (text_.selection.start.par() == next_par) {
1759                                 text_.selection.start.par(first_par);
1760                                 text_.selection.start.pos(
1761                                         text_.selection.start.pos() + first_par_size);
1762                         }
1763                         if (text_.selection.end.par() == next_par) {
1764                                 text_.selection.end.par(first_par);
1765                                 text_.selection.end.pos(
1766                                         text_.selection.end.pos() + first_par_size);
1767                         }
1768                 }
1769
1770                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
1771         }
1772 }
1773
1774
1775 void InsetText::getDrawFont(LyXFont & font) const
1776 {
1777         if (!owner())
1778                 return;
1779         owner()->getDrawFont(font);
1780 }
1781
1782
1783 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
1784 {
1785 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
1786 // And it probably does. You have to take a look at this John. (Lgb)
1787 #warning John, have a look here. (Lgb)
1788         ParagraphList::iterator pit = plist.begin();
1789         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
1790         ++pit;
1791         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
1792
1793         ParagraphList::iterator pend = plist.end();
1794         for (; pit != pend; ++pit)
1795                 paragraphs.push_back(*pit);
1796 }
1797
1798
1799 void InsetText::addPreview(PreviewLoader & loader) const
1800 {
1801         ParagraphList::const_iterator pit = paragraphs.begin();
1802         ParagraphList::const_iterator pend = paragraphs.end();
1803
1804         for (; pit != pend; ++pit) {
1805                 InsetList::const_iterator it  = pit->insetlist.begin();
1806                 InsetList::const_iterator end = pit->insetlist.end();
1807                 for (; it != end; ++it)
1808                         it->inset->addPreview(loader);
1809         }
1810 }