]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
reduce line noise
[features.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "EmbeddedFiles.h"
29 #include "ErrorList.h"
30 #include "factory.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "gettext.h"
35 #include "Intl.h"
36 #include "InsetIterator.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "LyXRC.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "Session.h"
50 #include "Text.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
53 #include "TexRow.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetRef.h"
60 #include "insets/InsetText.h"
61
62 #include "frontends/alert.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/lstrings.h"
73 #include "support/FileFilterList.h"
74 #include "support/filetools.h"
75 #include "support/Package.h"
76 #include "support/types.h"
77
78 #include <boost/current_function.hpp>
79
80 #include <cerrno>
81 #include <fstream>
82 #include <functional>
83 #include <iterator>
84 #include <vector>
85
86 using std::distance;
87 using std::endl;
88 using std::ifstream;
89 using std::istringstream;
90 using std::istream_iterator;
91 using std::make_pair;
92 using std::min;
93 using std::max;
94 using std::mem_fun_ref;
95 using std::string;
96 using std::vector;
97
98 namespace lyx {
99
100 using support::addPath;
101 using support::bformat;
102 using support::FileFilterList;
103 using support::FileName;
104 using support::fileSearch;
105 using support::makeDisplayPath;
106 using support::makeAbsPath;
107 using support::package;
108
109 namespace Alert = frontend::Alert;
110
111 namespace {
112
113 /// Return an inset of this class if it exists at the current cursor position
114 template <class T>
115 T * getInsetByCode(Cursor const & cur, InsetCode code)
116 {
117         DocIterator it = cur;
118         Inset * inset = it.nextInset();
119         if (inset && inset->lyxCode() == code)
120                 return static_cast<T*>(inset);
121         return 0;
122 }
123
124
125 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
126         bool same_content);
127
128 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
129         docstring const & contents)
130 {
131         DocIterator tmpdit = dit;
132
133         while (tmpdit) {
134                 Inset const * inset = tmpdit.nextInset();
135                 if (inset
136                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
137                     && (contents.empty() ||
138                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
139                         dit = tmpdit;
140                         return true;
141                 }
142                 tmpdit.forwardInset();
143         }
144
145         return false;
146 }
147
148
149 /// Looks for next inset with one of the given codes.
150 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
151         bool same_content)
152 {
153         docstring contents;
154         DocIterator tmpdit = dit;
155         tmpdit.forwardInset();
156         if (!tmpdit)
157                 return false;
158
159         if (same_content) {
160                 Inset const * inset = tmpdit.nextInset();
161                 if (inset
162                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
163                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
164                 }
165         }
166
167         if (!findNextInset(tmpdit, codes, contents)) {
168                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
169                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
170                         if (!findNextInset(tmpdit, codes, contents))
171                                 return false;
172                 } else
173                         return false;
174         }
175
176         dit = tmpdit;
177         return true;
178 }
179
180
181 /// Looks for next inset with the given code
182 void findInset(DocIterator & dit, InsetCode code, bool same_content)
183 {
184         findInset(dit, vector<InsetCode>(1, code), same_content);
185 }
186
187
188 /// Moves cursor to the next inset with one of the given codes.
189 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
190                bool same_content)
191 {
192         Cursor tmpcur = bv->cursor();
193         if (!findInset(tmpcur, codes, same_content)) {
194                 bv->cursor().message(_("No more insets"));
195                 return;
196         }
197
198         tmpcur.clearSelection();
199         bv->setCursor(tmpcur);
200 }
201
202
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
205 {
206         gotoInset(bv, vector<InsetCode>(1, code), same_content);
207 }
208
209
210 /// A map from a Text to the associated text metrics
211 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
212
213 } // anon namespace
214
215
216 /////////////////////////////////////////////////////////////////////
217 //
218 // BufferView
219 //
220 /////////////////////////////////////////////////////////////////////
221
222 struct BufferView::Private
223 {
224         Private(BufferView & bv): wh_(0), cursor_(bv),
225                 anchor_ref_(0), offset_ref_(0), need_centering_(false),
226                 last_inset_(0), gui_(0)
227         {}
228
229         ///
230         ScrollbarParameters scrollbarParameters_;
231         ///
232         ViewMetricsInfo metrics_info_;
233         ///
234         CoordCache coord_cache_;
235
236         /// Estimated average par height for scrollbar.
237         int wh_;
238         /// this is used to handle XSelection events in the right manner.
239         struct {
240                 CursorSlice cursor;
241                 CursorSlice anchor;
242                 bool set;
243         } xsel_cache_;
244         ///
245         Cursor cursor_;
246         ///
247         pit_type anchor_ref_;
248         ///
249         int offset_ref_;
250         ///
251         bool need_centering_;
252
253         /// keyboard mapping object.
254         Intl intl_;
255
256         /// last visited inset.
257         /** kept to send setMouseHover(false).
258           * Not owned, so don't delete.
259           */
260         Inset * last_inset_;
261
262         mutable TextMetricsCache text_metrics_;
263
264         /// Whom to notify.
265         /** Not owned, so don't delete.
266           */
267         frontend::GuiBufferViewDelegate * gui_;
268 };
269
270
271 BufferView::BufferView(Buffer & buf)
272         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
273 {
274         d->xsel_cache_.set = false;
275         d->intl_.initKeyMapper(lyxrc.use_kbmap);
276
277         d->cursor_.push(buffer_.inset());
278         d->cursor_.resetAnchor();
279         d->cursor_.setCurrentFont();
280
281         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
282                 graphics::Previews::get().generateBufferPreviews(buffer_);
283 }
284
285
286 BufferView::~BufferView()
287 {
288         // current buffer is going to be switched-off, save cursor pos
289         // Ideally, the whole cursor stack should be saved, but session
290         // currently can only handle bottom (whole document) level pit and pos.
291         // That is to say, if a cursor is in a nested inset, it will be
292         // restore to the left of the top level inset.
293         LastFilePosSection::FilePos fp;
294         fp.pit = d->cursor_.bottom().pit();
295         fp.pos = d->cursor_.bottom().pos();
296         LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
297
298         delete d;
299 }
300
301
302 Intl & BufferView::getIntl()
303 {
304         return d->intl_;
305 }
306
307
308 Intl const & BufferView::getIntl() const
309 {
310         return d->intl_;
311 }
312
313
314 CoordCache & BufferView::coordCache()
315 {
316         return d->coord_cache_;
317 }
318
319
320 CoordCache const & BufferView::coordCache() const
321 {
322         return d->coord_cache_;
323 }
324
325
326 Buffer & BufferView::buffer()
327 {
328         return buffer_;
329 }
330
331
332 Buffer const & BufferView::buffer() const
333 {
334         return buffer_;
335 }
336
337
338 bool BufferView::fitCursor()
339 {
340         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
341                 frontend::FontMetrics const & fm =
342                         theFontMetrics(d->cursor_.getFont().fontInfo());
343                 int const asc = fm.maxAscent();
344                 int const des = fm.maxDescent();
345                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
346                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
347                         return false;
348         }
349         center();
350         return true;
351 }
352
353
354 void BufferView::processUpdateFlags(Update::flags flags)
355 {
356         // last_inset_ points to the last visited inset. This pointer may become
357         // invalid because of keyboard editing. Since all such operations
358         // causes screen update(), I reset last_inset_ to avoid such a problem.
359         d->last_inset_ = 0;
360         // This is close to a hot-path.
361         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
362                 << "[fitcursor = " << (flags & Update::FitCursor)
363                 << ", forceupdate = " << (flags & Update::Force)
364                 << ", singlepar = " << (flags & Update::SinglePar)
365                 << "]  buffer: " << &buffer_);
366
367         // Update macro store
368         if (!(cursor().inMathed() && cursor().inMacroMode()))
369                 buffer_.updateMacros();
370
371         // Now do the first drawing step if needed. This consists on updating
372         // the CoordCache in updateMetrics().
373         // The second drawing step is done in WorkArea::redraw() if needed.
374
375         // Case when no explicit update is requested.
376         if (!flags) {
377                 // no need to redraw anything.
378                 d->metrics_info_.update_strategy = NoScreenUpdate;
379                 return;
380         }
381
382         if (flags == Update::Decoration) {
383                 d->metrics_info_.update_strategy = DecorationUpdate;
384                 buffer_.changed();
385                 return;
386         }
387
388         if (flags == Update::FitCursor
389                 || flags == (Update::Decoration | Update::FitCursor)) {
390                 bool const fit_cursor = fitCursor();
391                 // tell the frontend to update the screen if needed.
392                 if (fit_cursor) {
393                         updateMetrics();
394                         buffer_.changed();
395                         return;
396                 }
397                 if (flags & Update::Decoration) {
398                         d->metrics_info_.update_strategy = DecorationUpdate;
399                         buffer_.changed();
400                         return;
401                 }
402                 // no screen update is needed.
403                 d->metrics_info_.update_strategy = NoScreenUpdate;
404                 return;
405         }
406
407         bool const full_metrics = flags & Update::Force;
408
409         if (full_metrics || !singleParUpdate())
410                 // We have to update the full screen metrics.
411                 updateMetrics();
412
413         if (!(flags & Update::FitCursor)) {
414                 buffer_.changed();
415                 return;
416         }
417
418         //FIXME: updateMetrics() does not update paragraph position
419         // This is done at draw() time. So we need a redraw!
420         buffer_.changed();
421         if (!fitCursor())
422                 // The screen has already been updated thanks to the
423                 // 'buffer_.changed()' call three line above. So no need
424                 // to redraw again.
425                 return;
426
427         // The screen has been recentered around the cursor position so
428         // refresh it:
429         updateMetrics();
430         buffer_.changed();
431 }
432
433
434 void BufferView::updateScrollbar()
435 {
436         Text & t = buffer_.text();
437         TextMetrics & tm = d->text_metrics_[&t];
438
439         int const parsize = int(t.paragraphs().size() - 1);
440         if (d->anchor_ref_ >  parsize)  {
441                 d->anchor_ref_ = parsize;
442                 d->offset_ref_ = 0;
443         }
444
445         LYXERR(Debug::GUI, BOOST_CURRENT_FUNCTION
446                 << " Updating scrollbar: height: " << t.paragraphs().size()
447                 << " curr par: " << d->cursor_.bottom().pit()
448                 << " default height " << defaultRowHeight());
449
450         // It would be better to fix the scrollbar to understand
451         // values in [0..1] and divide everything by wh
452
453         // estimated average paragraph height:
454         if (d->wh_ == 0)
455                 d->wh_ = height_ / 4;
456
457         int h = tm.parMetrics(d->anchor_ref_).height();
458
459         // Normalize anchor/offset (MV):
460         while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
461                 d->anchor_ref_++;
462                 d->offset_ref_ -= h;
463                 h = tm.parMetrics(d->anchor_ref_).height();
464         }
465         // Look at paragraph heights on-screen
466         int sumh = 0;
467         int nh = 0;
468         for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
469                 if (sumh > height_)
470                         break;
471                 int const h2 = tm.parMetrics(pit).height();
472                 sumh += h2;
473                 nh++;
474         }
475
476         BOOST_ASSERT(nh);
477         int const hav = sumh / nh;
478         // More realistic average paragraph height
479         if (hav > d->wh_)
480                 d->wh_ = hav;
481
482         BOOST_ASSERT(h);
483         d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
484         d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
485         d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
486 }
487
488
489 ScrollbarParameters const & BufferView::scrollbarParameters() const
490 {
491         return d->scrollbarParameters_;
492 }
493
494
495 void BufferView::scrollDocView(int value)
496 {
497         LYXERR(Debug::GUI, BOOST_CURRENT_FUNCTION << "[ value = " << value << "]");
498
499         Text & t = buffer_.text();
500         TextMetrics & tm = d->text_metrics_[&t];
501
502         float const bar = value / float(d->wh_ * t.paragraphs().size());
503
504         d->anchor_ref_ = int(bar * t.paragraphs().size());
505         if (d->anchor_ref_ >  int(t.paragraphs().size()) - 1)
506                 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
507
508         tm.redoParagraph(d->anchor_ref_);
509         int const h = tm.parMetrics(d->anchor_ref_).height();
510         d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
511         updateMetrics();
512         buffer_.changed();
513 }
514
515
516 void BufferView::setCursorFromScrollbar()
517 {
518         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
519
520         int const height = 2 * defaultRowHeight();
521         int const first = height;
522         int const last = height_ - height;
523         Cursor & cur = d->cursor_;
524
525         switch (cursorStatus(cur)) {
526         case CUR_ABOVE:
527                 // We reset the cursor because cursorStatus() does not
528                 // work when the cursor is within mathed.
529                 cur.reset(buffer_.inset());
530                 tm.setCursorFromCoordinates(cur, 0, first);
531                 cur.clearSelection();
532                 break;
533         case CUR_BELOW:
534                 // We reset the cursor because cursorStatus() does not
535                 // work when the cursor is within mathed.
536                 cur.reset(buffer_.inset());
537                 tm.setCursorFromCoordinates(cur, 0, last);
538                 cur.clearSelection();
539                 break;
540         case CUR_INSIDE:
541                 int const y = getPos(cur, cur.boundary()).y_;
542                 int const newy = min(last, max(y, first));
543                 if (y != newy) {
544                         cur.reset(buffer_.inset());
545                         tm.setCursorFromCoordinates(cur, 0, newy);
546                 }
547         }
548 }
549
550
551 Change const BufferView::getCurrentChange() const
552 {
553         if (!d->cursor_.selection())
554                 return Change(Change::UNCHANGED);
555
556         DocIterator dit = d->cursor_.selectionBegin();
557         return dit.paragraph().lookupChange(dit.pos());
558 }
559
560
561 // this could be used elsewhere as well?
562 // FIXME: This does not work within mathed!
563 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
564 {
565         Point const p = getPos(dit, dit.boundary());
566         if (p.y_ < 0)
567                 return CUR_ABOVE;
568         if (p.y_ > workHeight())
569                 return CUR_BELOW;
570         return CUR_INSIDE;
571 }
572
573
574 void BufferView::saveBookmark(unsigned int idx)
575 {
576         // tenatively save bookmark, id and pos will be used to
577         // acturately locate a bookmark in a 'live' lyx session.
578         // pit and pos will be updated with bottom level pit/pos
579         // when lyx exits.
580         LyX::ref().session().bookmarks().save(
581                 buffer_.fileName(),
582                 d->cursor_.bottom().pit(),
583                 d->cursor_.bottom().pos(),
584                 d->cursor_.paragraph().id(),
585                 d->cursor_.pos(),
586                 idx
587         );
588         if (idx)
589                 // emit message signal.
590                 message(_("Save bookmark"));
591 }
592
593
594 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
595         int top_id, pos_type top_pos)
596 {
597         bool success = false;
598         DocIterator doc_it;
599
600         d->cursor_.clearSelection();
601
602         // if a valid par_id is given, try it first
603         // This is the case for a 'live' bookmark when unique paragraph ID
604         // is used to track bookmarks.
605         if (top_id > 0) {
606                 ParIterator par = buffer_.getParFromID(top_id);
607                 if (par != buffer_.par_iterator_end()) {
608                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
609                         // Some slices of the iterator may not be
610                         // reachable (e.g. closed collapsable inset)
611                         // so the dociterator may need to be
612                         // shortened. Otherwise, setCursor may crash
613                         // lyx when the cursor can not be set to these
614                         // insets.
615                         size_t const n = doc_it.depth();
616                         for (size_t i = 0; i < n; ++i)
617                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
618                                         doc_it.resize(i);
619                                         break;
620                                 }
621                         success = true;
622                 }
623         }
624
625         // if top_id == 0, or searching through top_id failed
626         // This is the case for a 'restored' bookmark when only bottom
627         // (document level) pit was saved. Because of this, bookmark
628         // restoration is inaccurate. If a bookmark was within an inset,
629         // it will be restored to the left of the outmost inset that contains
630         // the bookmark.
631         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
632                 doc_it = doc_iterator_begin(buffer_.inset());
633                 doc_it.pit() = bottom_pit;
634                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
635                 success = true;
636         }
637
638         if (success) {
639                 // Note: only bottom (document) level pit is set.
640                 setCursor(doc_it);
641                 // set the current font.
642                 d->cursor_.setCurrentFont();
643                 // center the screen on this new position.
644                 center();
645         }
646
647         return success;
648 }
649
650
651 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
652 {
653         if (lyxrc.rtl_support) {
654                 if (d->cursor_.real_current_font.isRightToLeft()) {
655                         if (d->intl_.keymap == Intl::PRIMARY)
656                                 d->intl_.keyMapSec();
657                 } else {
658                         if (d->intl_.keymap == Intl::SECONDARY)
659                                 d->intl_.keyMapPrim();
660                 }
661         }
662
663         d->intl_.getTransManager().translateAndInsert(c, t, cur);
664 }
665
666
667 int BufferView::workWidth() const
668 {
669         return width_;
670 }
671
672
673 void BufferView::updateOffsetRef()
674 {
675         // No need to update d->offset_ref_ in this case.
676         if (!d->need_centering_)
677                 return;
678
679         // We are not properly started yet, delay until resizing is
680         // done.
681         if (height_ == 0)
682                 return;
683
684         CursorSlice & bot = d->cursor_.bottom();
685         TextMetrics & tm = d->text_metrics_[bot.text()];
686         ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
687         int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
688         d->offset_ref_ = y + pm.ascent() - height_ / 2;
689
690         d->need_centering_ = false;
691 }
692
693
694 void BufferView::center()
695 {
696         d->anchor_ref_ = d->cursor_.bottom().pit();
697         d->need_centering_ = true;
698 }
699
700
701 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
702 {
703         FuncStatus flag;
704
705         Cursor & cur = d->cursor_;
706
707         switch (cmd.action) {
708
709         case LFUN_UNDO:
710                 flag.enabled(buffer_.undo().hasUndoStack());
711                 break;
712         case LFUN_REDO:
713                 flag.enabled(buffer_.undo().hasRedoStack());
714                 break;
715         case LFUN_FILE_INSERT:
716         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
717         case LFUN_FILE_INSERT_PLAINTEXT:
718         case LFUN_BOOKMARK_SAVE:
719                 // FIXME: Actually, these LFUNS should be moved to Text
720                 flag.enabled(cur.inTexted());
721                 break;
722         case LFUN_FONT_STATE:
723         case LFUN_LABEL_INSERT:
724         case LFUN_INFO_INSERT:
725         case LFUN_PARAGRAPH_GOTO:
726         case LFUN_NOTE_NEXT:
727         case LFUN_REFERENCE_NEXT:
728         case LFUN_WORD_FIND:
729         case LFUN_WORD_REPLACE:
730         case LFUN_MARK_OFF:
731         case LFUN_MARK_ON:
732         case LFUN_MARK_TOGGLE:
733         case LFUN_SCREEN_RECENTER:
734         case LFUN_BIBTEX_DATABASE_ADD:
735         case LFUN_BIBTEX_DATABASE_DEL:
736         case LFUN_WORDS_COUNT:
737         case LFUN_NEXT_INSET_TOGGLE:
738                 flag.enabled(true);
739                 break;
740
741         case LFUN_LABEL_GOTO: {
742                 flag.enabled(!cmd.argument().empty()
743                     || getInsetByCode<InsetRef>(cur, REF_CODE));
744                 break;
745         }
746
747         case LFUN_CHANGES_TRACK:
748                 flag.enabled(true);
749                 flag.setOnOff(buffer_.params().trackChanges);
750                 break;
751
752         case LFUN_CHANGES_OUTPUT:
753                 flag.enabled(true);
754                 flag.setOnOff(buffer_.params().outputChanges);
755                 break;
756
757         case LFUN_CHANGES_MERGE:
758         case LFUN_CHANGE_NEXT:
759         case LFUN_ALL_CHANGES_ACCEPT:
760         case LFUN_ALL_CHANGES_REJECT:
761                 // TODO: context-sensitive enabling of LFUNs
762                 // In principle, these command should only be enabled if there
763                 // is a change in the document. However, without proper
764                 // optimizations, this will inevitably result in poor performance.
765                 flag.enabled(true);
766                 break;
767
768         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
769                 flag.setOnOff(buffer_.params().compressed);
770                 break;
771         }
772         
773         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
774                 flag.setOnOff(buffer_.params().embedded);
775                 break;
776         }
777
778         case LFUN_SCREEN_UP:
779         case LFUN_SCREEN_DOWN:
780                 flag.enabled(true);
781                 break;
782
783         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
784         // everywhere else before this can enabled:
785         case LFUN_SCREEN_UP_SELECT:
786         case LFUN_SCREEN_DOWN_SELECT:
787                 flag.enabled(false);
788                 break;
789
790         case LFUN_LAYOUT_TABULAR:
791                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
792                 break;
793
794         case LFUN_LAYOUT:
795         case LFUN_LAYOUT_PARAGRAPH:
796                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
797                 break;
798
799         case LFUN_INSET_SETTINGS: {
800                 InsetCode code = cur.inset().lyxCode();
801                 bool enable = false;
802                 switch (code) {
803                         case TABULAR_CODE:
804                                 enable = cmd.argument() == "tabular";
805                                 break;
806                         case ERT_CODE:
807                                 enable = cmd.argument() == "ert";
808                                 break;
809                         case FLOAT_CODE:
810                                 enable = cmd.argument() == "float";
811                                 break;
812                         case WRAP_CODE:
813                                 enable = cmd.argument() == "wrap";
814                                 break;
815                         case NOTE_CODE:
816                                 enable = cmd.argument() == "note";
817                                 break;
818                         case BRANCH_CODE:
819                                 enable = cmd.argument() == "branch";
820                                 break;
821                         case BOX_CODE:
822                                 enable = cmd.argument() == "box";
823                                 break;
824                         case LISTINGS_CODE:
825                                 enable = cmd.argument() == "listings";
826                                 break;
827                         default:
828                                 break;
829                 }
830                 flag.enabled(enable);
831                 break;
832         }
833
834         case LFUN_DIALOG_SHOW_NEW_INSET:
835                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
836                         cur.inset().lyxCode() != LISTINGS_CODE);
837                 if (cur.inset().lyxCode() == CAPTION_CODE) {
838                         FuncStatus flag;
839                         if (cur.inset().getStatus(cur, cmd, flag))
840                                 return flag;
841                 }
842                 break;
843
844         default:
845                 flag.enabled(false);
846         }
847
848         return flag;
849 }
850
851
852 Update::flags BufferView::dispatch(FuncRequest const & cmd)
853 {
854         //lyxerr << BOOST_CURRENT_FUNCTION
855         //       << [ cmd = " << cmd << "]" << endl;
856
857         // Make sure that the cached BufferView is correct.
858         LYXERR(Debug::ACTION, BOOST_CURRENT_FUNCTION
859                 << " action[" << cmd.action << ']'
860                 << " arg[" << to_utf8(cmd.argument()) << ']'
861                 << " x[" << cmd.x << ']'
862                 << " y[" << cmd.y << ']'
863                 << " button[" << cmd.button() << ']');
864
865         Cursor & cur = d->cursor_;
866         // Default Update flags.
867         Update::flags updateFlags = Update::Force | Update::FitCursor;
868
869         switch (cmd.action) {
870
871         case LFUN_UNDO:
872                 cur.message(_("Undo"));
873                 cur.clearSelection();
874                 if (!cur.textUndo()) {
875                         cur.message(_("No further undo information"));
876                         updateFlags = Update::None;
877                 }
878                 break;
879
880         case LFUN_REDO:
881                 cur.message(_("Redo"));
882                 cur.clearSelection();
883                 if (!cur.textRedo()) {
884                         cur.message(_("No further redo information"));
885                         updateFlags = Update::None;
886                 }
887                 break;
888
889         case LFUN_FILE_INSERT:
890                 // FIXME UNICODE
891                 menuInsertLyXFile(to_utf8(cmd.argument()));
892                 break;
893
894         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
895                 // FIXME UNICODE
896                 insertPlaintextFile(to_utf8(cmd.argument()), true);
897                 break;
898
899         case LFUN_FILE_INSERT_PLAINTEXT:
900                 // FIXME UNICODE
901                 insertPlaintextFile(to_utf8(cmd.argument()), false);
902                 break;
903
904         case LFUN_FONT_STATE:
905                 cur.message(cur.currentState());
906                 break;
907
908         case LFUN_BOOKMARK_SAVE:
909                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
910                 break;
911
912         case LFUN_LABEL_GOTO: {
913                 docstring label = cmd.argument();
914                 if (label.empty()) {
915                         InsetRef * inset =
916                                 getInsetByCode<InsetRef>(d->cursor_,
917                                                          REF_CODE);
918                         if (inset) {
919                                 label = inset->getParam("reference");
920                                 // persistent=false: use temp_bookmark
921                                 saveBookmark(0);
922                         }
923                 }
924
925                 if (!label.empty())
926                         gotoLabel(label);
927                 break;
928         }
929
930         case LFUN_PARAGRAPH_GOTO: {
931                 int const id = convert<int>(to_utf8(cmd.argument()));
932                 int i = 0;
933                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
934                         b = theBufferList().next(b)) {
935
936                         ParIterator par = b->getParFromID(id);
937                         if (par == b->par_iterator_end()) {
938                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
939                         } else {
940                                 LYXERR(Debug::INFO, "Paragraph " << par->id()
941                                         << " found in buffer `"
942                                         << b->absFileName() << "'.");
943
944                                 if (b == &buffer_) {
945                                         // Set the cursor
946                                         setCursor(makeDocIterator(par, 0));
947                                 } else {
948                                         // Switch to other buffer view and resend cmd
949                                         theLyXFunc().dispatch(FuncRequest(
950                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
951                                         theLyXFunc().dispatch(cmd);
952                                         updateFlags = Update::None;
953                                 }
954                                 break;
955                         }
956                         ++i;
957                 }
958                 break;
959         }
960
961         case LFUN_NOTE_NEXT:
962                 gotoInset(this, NOTE_CODE, false);
963                 break;
964
965         case LFUN_REFERENCE_NEXT: {
966                 vector<InsetCode> tmp;
967                 tmp.push_back(LABEL_CODE);
968                 tmp.push_back(REF_CODE);
969                 gotoInset(this, tmp, true);
970                 break;
971         }
972
973         case LFUN_CHANGES_TRACK:
974                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
975                 break;
976
977         case LFUN_CHANGES_OUTPUT:
978                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
979                 if (buffer_.params().outputChanges) {
980                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
981                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
982                                           LaTeXFeatures::isAvailable("xcolor");
983
984                         if (!dvipost && !xcolorsoul) {
985                                 Alert::warning(_("Changes not shown in LaTeX output"),
986                                                _("Changes will not be highlighted in LaTeX output, "
987                                                  "because neither dvipost nor xcolor/soul are installed.\n"
988                                                  "Please install these packages or redefine "
989                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
990                         } else if (!xcolorsoul) {
991                                 Alert::warning(_("Changes not shown in LaTeX output"),
992                                                _("Changes will not be highlighted in LaTeX output "
993                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
994                                                  "Please install both packages or redefine "
995                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
996                         }
997                 }
998                 break;
999
1000         case LFUN_CHANGE_NEXT:
1001                 findNextChange(this);
1002                 break;
1003
1004         case LFUN_CHANGES_MERGE:
1005                 if (findNextChange(this))
1006                         showDialog("changes");
1007                 break;
1008
1009         case LFUN_ALL_CHANGES_ACCEPT:
1010                 // select complete document
1011                 d->cursor_.reset(buffer_.inset());
1012                 d->cursor_.selHandle(true);
1013                 buffer_.text().cursorBottom(d->cursor_);
1014                 // accept everything in a single step to support atomic undo
1015                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1016                 break;
1017
1018         case LFUN_ALL_CHANGES_REJECT:
1019                 // select complete document
1020                 d->cursor_.reset(buffer_.inset());
1021                 d->cursor_.selHandle(true);
1022                 buffer_.text().cursorBottom(d->cursor_);
1023                 // reject everything in a single step to support atomic undo
1024                 // Note: reject does not work recursively; the user may have to repeat the operation
1025                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1026                 break;
1027
1028         case LFUN_WORD_FIND:
1029                 find(this, cmd);
1030                 break;
1031
1032         case LFUN_WORD_REPLACE: {
1033                 bool has_deleted = false;
1034                 if (cur.selection()) {
1035                         DocIterator beg = cur.selectionBegin();
1036                         DocIterator end = cur.selectionEnd();
1037                         if (beg.pit() == end.pit()) {
1038                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1039                                         if (cur.paragraph().isDeleted(p))
1040                                                 has_deleted = true;
1041                                 }
1042                         }
1043                 }
1044                 replace(this, cmd, has_deleted);
1045                 break;
1046         }
1047
1048         case LFUN_MARK_OFF:
1049                 cur.clearSelection();
1050                 cur.resetAnchor();
1051                 cur.message(from_utf8(N_("Mark off")));
1052                 break;
1053
1054         case LFUN_MARK_ON:
1055                 cur.clearSelection();
1056                 cur.mark() = true;
1057                 cur.resetAnchor();
1058                 cur.message(from_utf8(N_("Mark on")));
1059                 break;
1060
1061         case LFUN_MARK_TOGGLE:
1062                 cur.clearSelection();
1063                 if (cur.mark()) {
1064                         cur.mark() = false;
1065                         cur.message(from_utf8(N_("Mark removed")));
1066                 } else {
1067                         cur.mark() = true;
1068                         cur.message(from_utf8(N_("Mark set")));
1069                 }
1070                 cur.resetAnchor();
1071                 break;
1072
1073         case LFUN_SCREEN_RECENTER:
1074                 center();
1075                 break;
1076
1077         case LFUN_BIBTEX_DATABASE_ADD: {
1078                 Cursor tmpcur = d->cursor_;
1079                 findInset(tmpcur, BIBTEX_CODE, false);
1080                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1081                                                 BIBTEX_CODE);
1082                 if (inset) {
1083                         if (inset->addDatabase(to_utf8(cmd.argument())))
1084                                 buffer_.updateBibfilesCache();
1085                 }
1086                 break;
1087         }
1088
1089         case LFUN_BIBTEX_DATABASE_DEL: {
1090                 Cursor tmpcur = d->cursor_;
1091                 findInset(tmpcur, BIBTEX_CODE, false);
1092                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1093                                                 BIBTEX_CODE);
1094                 if (inset) {
1095                         if (inset->delDatabase(to_utf8(cmd.argument())))
1096                                 buffer_.updateBibfilesCache();
1097                 }
1098                 break;
1099         }
1100
1101         case LFUN_WORDS_COUNT: {
1102                 DocIterator from, to;
1103                 if (cur.selection()) {
1104                         from = cur.selectionBegin();
1105                         to = cur.selectionEnd();
1106                 } else {
1107                         from = doc_iterator_begin(buffer_.inset());
1108                         to = doc_iterator_end(buffer_.inset());
1109                 }
1110                 int const count = countWords(from, to);
1111                 docstring message;
1112                 if (count != 1) {
1113                         if (cur.selection())
1114                                 message = bformat(_("%1$d words in selection."),
1115                                           count);
1116                                 else
1117                                         message = bformat(_("%1$d words in document."),
1118                                                           count);
1119                 }
1120                 else {
1121                         if (cur.selection())
1122                                 message = _("One word in selection.");
1123                         else
1124                                 message = _("One word in document.");
1125                 }
1126
1127                 Alert::information(_("Count words"), message);
1128         }
1129                 break;
1130
1131         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1132                 // turn compression on/off
1133                 buffer_.params().compressed = !buffer_.params().compressed;
1134                 break;
1135         
1136         case LFUN_BUFFER_TOGGLE_EMBEDDING:
1137                 // turn embedding on/off
1138                 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1139                 break;
1140
1141         case LFUN_NEXT_INSET_TOGGLE: {
1142                 // this is the real function we want to invoke
1143                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1144                 // if there is an inset at cursor, see whether it
1145                 // wants to toggle.
1146                 Inset * inset = cur.nextInset();
1147                 if (inset) {
1148                         if (inset->isActive()) {
1149                                 Cursor tmpcur = cur;
1150                                 tmpcur.pushBackward(*inset);
1151                                 inset->dispatch(tmpcur, tmpcmd);
1152                                 if (tmpcur.result().dispatched()) {
1153                                         cur.dispatched();
1154                                 }
1155                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1156                                 inset->edit(cur, true);
1157                         }
1158                 }
1159                 // if it did not work, try the underlying inset.
1160                 if (!cur.result().dispatched())
1161                         cur.dispatch(tmpcmd);
1162
1163                 if (cur.result().dispatched())
1164                         cur.clearSelection();
1165
1166                 break;
1167         }
1168
1169         case LFUN_SCREEN_UP:
1170         case LFUN_SCREEN_DOWN: {
1171                 Point p = getPos(cur, cur.boundary());
1172                 if (p.y_ < 0 || p.y_ > height_) {
1173                         // The cursor is off-screen so recenter before proceeding.
1174                         center();
1175                         updateMetrics();
1176                         //FIXME: updateMetrics() does not update paragraph position
1177                         // This is done at draw() time. So we need a redraw!
1178                         // But no screen update is needed.
1179                         d->metrics_info_.update_strategy = NoScreenUpdate;
1180                         buffer_.changed();
1181                         p = getPos(cur, cur.boundary());
1182                 }
1183                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1184                 cur.reset(buffer_.inset());
1185                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1186                 //FIXME: what to do with cur.x_target()?
1187                 cur.finishUndo();
1188                 // The metrics are already up to date. see scroll()
1189                 updateFlags = Update::None;
1190                 break;
1191         }
1192
1193         case LFUN_SCREEN_UP_SELECT:
1194         case LFUN_SCREEN_DOWN_SELECT: {
1195                 cur.selHandle(true);
1196                 size_t initial_depth = cur.depth();
1197                 Point const p = getPos(cur, cur.boundary());
1198                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1199                 // FIXME: We need to verify if the cursor stayed within an inset...
1200                 //cur.reset(buffer_.inset());
1201                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1202                 cur.finishUndo();
1203                 while (cur.depth() > initial_depth) {
1204                         cur.forwardInset();
1205                 }
1206                 // FIXME: we need to do a redraw again because of the selection
1207                 // But no screen update is needed.
1208                 d->metrics_info_.update_strategy = NoScreenUpdate;
1209                 buffer_.changed();
1210                 updateFlags = Update::Force | Update::FitCursor;
1211                 break;
1212         }
1213
1214         default:
1215                 updateFlags = Update::None;
1216         }
1217
1218         return updateFlags;
1219 }
1220
1221
1222 docstring const BufferView::requestSelection()
1223 {
1224         Cursor & cur = d->cursor_;
1225
1226         if (!cur.selection()) {
1227                 d->xsel_cache_.set = false;
1228                 return docstring();
1229         }
1230
1231         if (!d->xsel_cache_.set ||
1232             cur.top() != d->xsel_cache_.cursor ||
1233             cur.anchor_.top() != d->xsel_cache_.anchor)
1234         {
1235                 d->xsel_cache_.cursor = cur.top();
1236                 d->xsel_cache_.anchor = cur.anchor_.top();
1237                 d->xsel_cache_.set = cur.selection();
1238                 return cur.selectionAsString(false);
1239         }
1240         return docstring();
1241 }
1242
1243
1244 void BufferView::clearSelection()
1245 {
1246         d->cursor_.clearSelection();
1247         // Clear the selection buffer. Otherwise a subsequent
1248         // middle-mouse-button paste would use the selection buffer,
1249         // not the more current external selection.
1250         cap::clearSelection();
1251         d->xsel_cache_.set = false;
1252         // The buffer did not really change, but this causes the
1253         // redraw we need because we cleared the selection above.
1254         buffer_.changed();
1255 }
1256
1257
1258 void BufferView::resize(int width, int height)
1259 {
1260         // Update from work area
1261         width_ = width;
1262         height_ = height;
1263
1264         updateMetrics();
1265 }
1266
1267
1268 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1269 {
1270         TextMetrics & tm = d->text_metrics_[&text];
1271         Inset * inset = tm.checkInsetHit(x, y);
1272         if (!inset)
1273                 return 0;
1274
1275         if (!inset->descendable())
1276                 // No need to go further down if the inset is not
1277                 // descendable.
1278                 return inset;
1279
1280         size_t cell_number = inset->nargs();
1281         // Check all the inner cell.
1282         for (size_t i = 0; i != cell_number; ++i) {
1283                 Text const * inner_text = inset->getText(i);
1284                 if (inner_text) {
1285                         // Try deeper.
1286                         Inset const * inset_deeper =
1287                                 getCoveringInset(*inner_text, x, y);
1288                         if (inset_deeper)
1289                                 return inset_deeper;
1290                 }
1291         }
1292
1293         return inset;
1294 }
1295
1296
1297 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1298 {
1299         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1300
1301         // This is only called for mouse related events including
1302         // LFUN_FILE_OPEN generated by drag-and-drop.
1303         FuncRequest cmd = cmd0;
1304
1305         Cursor cur(*this);
1306         cur.push(buffer_.inset());
1307         cur.selection() = d->cursor_.selection();
1308
1309         // Either the inset under the cursor or the
1310         // surrounding Text will handle this event.
1311
1312         // make sure we stay within the screen...
1313         cmd.y = min(max(cmd.y, -1), height_);
1314
1315         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1316
1317                 // Get inset under mouse, if there is one.
1318                 Inset const * covering_inset =
1319                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1320                 if (covering_inset == d->last_inset_)
1321                         // Same inset, no need to do anything...
1322                         return;
1323
1324                 bool need_redraw = false;
1325                 // const_cast because of setMouseHover().
1326                 Inset * inset = const_cast<Inset *>(covering_inset);
1327                 if (d->last_inset_)
1328                         // Remove the hint on the last hovered inset (if any).
1329                         need_redraw |= d->last_inset_->setMouseHover(false);
1330                 if (inset)
1331                         // Highlighted the newly hovered inset (if any).
1332                         need_redraw |= inset->setMouseHover(true);
1333                 d->last_inset_ = inset;
1334                 if (!need_redraw)
1335                         return;
1336
1337                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1338                 // not expose the button for redraw. We adjust here the metrics dimension
1339                 // to enable a full redraw in any case as this is not costly.
1340                 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
1341                 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1342                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1343                 int y1 = firstpm.second->position() - firstpm.second->ascent();
1344                 int y2 = lastpm.second->position() + lastpm.second->descent();
1345                 d->metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1346                         FullScreenUpdate, buffer_.text().paragraphs().size());
1347                 // Reinitialize anchor to first pit.
1348                 d->anchor_ref_ = firstpm.first;
1349                 d->offset_ref_ = -y1;
1350                 LYXERR(Debug::PAINTING,
1351                          "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1352                         << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1353                         << " pit1: " << firstpm.first << " pit2: " << lastpm.first);
1354
1355                 // This event (moving without mouse click) is not passed further.
1356                 // This should be changed if it is further utilized.
1357                 buffer_.changed();
1358                 return;
1359         }
1360
1361         // Build temporary cursor.
1362         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1363
1364         // Put anchor at the same position.
1365         cur.resetAnchor();
1366
1367         // Try to dispatch to an non-editable inset near this position
1368         // via the temp cursor. If the inset wishes to change the real
1369         // cursor it has to do so explicitly by using
1370         //  cur.bv().cursor() = cur;  (or similar)
1371         if (inset)
1372                 inset->dispatch(cur, cmd);
1373
1374         // Now dispatch to the temporary cursor. If the real cursor should
1375         // be modified, the inset's dispatch has to do so explicitly.
1376         if (!cur.result().dispatched())
1377                 cur.dispatch(cmd);
1378
1379         //Do we have a selection?
1380         theSelection().haveSelection(cursor().selection());
1381
1382         // If the command has been dispatched,
1383         if (cur.result().dispatched()
1384                 // an update is asked,
1385                 && cur.result().update())
1386                 processUpdateFlags(cur.result().update());
1387 }
1388
1389
1390 void BufferView::scroll(int y)
1391 {
1392         if (y > 0)
1393                 scrollDown(y);
1394         else if (y < 0)
1395                 scrollUp(-y);
1396 }
1397
1398
1399 void BufferView::scrollDown(int offset)
1400 {
1401         Text * text = &buffer_.text();
1402         TextMetrics & tm = d->text_metrics_[text];
1403         int ymax = height_ + offset;
1404         while (true) {
1405                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1406                 int bottom_pos = last.second->position() + last.second->descent();
1407                 if (last.first + 1 == int(text->paragraphs().size())) {
1408                         if (bottom_pos <= height_)
1409                                 return;
1410                         offset = min(offset, bottom_pos - height_);
1411                         break;
1412                 }
1413                 if (bottom_pos > ymax)
1414                         break;
1415                 tm.newParMetricsDown();
1416         }
1417         d->offset_ref_ += offset;
1418         updateMetrics();
1419         buffer_.changed();
1420 }
1421
1422
1423 void BufferView::scrollUp(int offset)
1424 {
1425         Text * text = &buffer_.text();
1426         TextMetrics & tm = d->text_metrics_[text];
1427         int ymin = - offset;
1428         while (true) {
1429                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1430                 int top_pos = first.second->position() - first.second->ascent();
1431                 if (first.first == 0) {
1432                         if (top_pos >= 0)
1433                                 return;
1434                         offset = min(offset, - top_pos);
1435                         break;
1436                 }
1437                 if (top_pos < ymin)
1438                         break;
1439                 tm.newParMetricsUp();
1440         }
1441         d->offset_ref_ -= offset;
1442         updateMetrics();
1443         buffer_.changed();
1444 }
1445
1446
1447 void BufferView::setCursorFromRow(int row)
1448 {
1449         int tmpid = -1;
1450         int tmppos = -1;
1451
1452         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1453
1454         d->cursor_.reset(buffer_.inset());
1455         if (tmpid == -1)
1456                 buffer_.text().setCursor(d->cursor_, 0, 0);
1457         else
1458                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1459 }
1460
1461
1462 void BufferView::gotoLabel(docstring const & label)
1463 {
1464         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1465                 vector<docstring> labels;
1466                 it->getLabelList(buffer_, labels);
1467                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1468                         setCursor(it);
1469                         processUpdateFlags(Update::FitCursor);
1470                         return;
1471                 }
1472         }
1473 }
1474
1475
1476 TextMetrics const & BufferView::textMetrics(Text const * t) const
1477 {
1478         return const_cast<BufferView *>(this)->textMetrics(t);
1479 }
1480
1481
1482 TextMetrics & BufferView::textMetrics(Text const * t)
1483 {
1484         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1485         if (tmc_it == d->text_metrics_.end()) {
1486                 tmc_it = d->text_metrics_.insert(
1487                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1488         }
1489         return tmc_it->second;
1490 }
1491
1492
1493 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1494                 pit_type pit) const
1495 {
1496         return textMetrics(t).parMetrics(pit);
1497 }
1498
1499
1500 int BufferView::workHeight() const
1501 {
1502         return height_;
1503 }
1504
1505
1506 void BufferView::setCursor(DocIterator const & dit)
1507 {
1508         size_t const n = dit.depth();
1509         for (size_t i = 0; i < n; ++i)
1510                 dit[i].inset().edit(d->cursor_, true);
1511
1512         d->cursor_.setCursor(dit);
1513         d->cursor_.selection() = false;
1514 }
1515
1516
1517 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1518 {
1519         // Would be wrong to delete anything if we have a selection.
1520         if (cur.selection())
1521                 return false;
1522
1523         bool need_anchor_change = false;
1524         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1525                 need_anchor_change);
1526
1527         if (need_anchor_change)
1528                 cur.resetAnchor();
1529
1530         if (!changed)
1531                 return false;
1532
1533         updateLabels(buffer_);
1534
1535         updateMetrics();
1536         buffer_.changed();
1537         return true;
1538 }
1539
1540
1541 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1542 {
1543         BOOST_ASSERT(&cur.bv() == this);
1544
1545         if (!select)
1546                 // this event will clear selection so we save selection for
1547                 // persistent selection
1548                 cap::saveSelection(cursor());
1549
1550         // Has the cursor just left the inset?
1551         bool badcursor = false;
1552         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1553         if (leftinset)
1554                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1555
1556         // FIXME: shift-mouse selection doesn't work well across insets.
1557         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1558
1559         // do the dEPM magic if needed
1560         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1561         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1562         // the leftinset bool would not be necessary (badcursor instead).
1563         bool update = leftinset;
1564         if (!do_selection && !badcursor && d->cursor_.inTexted())
1565                 update |= checkDepm(cur, d->cursor_);
1566
1567         // if the cursor was in an empty script inset and the new
1568         // position is in the nucleus of the inset, notifyCursorLeaves
1569         // will kill the script inset itself. So we check all the
1570         // elements of the cursor to make sure that they are correct.
1571         // For an example, see bug 2933:
1572         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1573         // The code below could maybe be moved to a DocIterator method.
1574         //lyxerr << "cur before " << cur <<std::endl;
1575         DocIterator dit(cur.inset());
1576         dit.push_back(cur.bottom());
1577         size_t i = 1;
1578         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1579                 dit.push_back(cur[i]);
1580                 ++i;
1581         }
1582         //lyxerr << "5 cur after" << dit <<std::endl;
1583
1584         d->cursor_.setCursor(dit);
1585         d->cursor_.boundary(cur.boundary());
1586         if (do_selection)
1587                 d->cursor_.setSelection();
1588         else
1589                 d->cursor_.clearSelection();
1590
1591         d->cursor_.finishUndo();
1592         d->cursor_.setCurrentFont();
1593         return update;
1594 }
1595
1596
1597 void BufferView::putSelectionAt(DocIterator const & cur,
1598                                 int length, bool backwards)
1599 {
1600         d->cursor_.clearSelection();
1601
1602         setCursor(cur);
1603
1604         if (length) {
1605                 if (backwards) {
1606                         d->cursor_.pos() += length;
1607                         d->cursor_.setSelection(d->cursor_, -length);
1608                 } else
1609                         d->cursor_.setSelection(d->cursor_, length);
1610         }
1611 }
1612
1613
1614 Cursor & BufferView::cursor()
1615 {
1616         return d->cursor_;
1617 }
1618
1619
1620 Cursor const & BufferView::cursor() const
1621 {
1622         return d->cursor_;
1623 }
1624
1625
1626 pit_type BufferView::anchor_ref() const
1627 {
1628         return d->anchor_ref_;
1629 }
1630
1631
1632 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1633 {
1634         return d->metrics_info_;
1635 }
1636
1637
1638 bool BufferView::singleParUpdate()
1639 {
1640         Text & buftext = buffer_.text();
1641         pit_type const bottom_pit = d->cursor_.bottom().pit();
1642         TextMetrics & tm = textMetrics(&buftext);
1643         int old_height = tm.parMetrics(bottom_pit).height();
1644
1645         // In Single Paragraph mode, rebreak only
1646         // the (main text, not inset!) paragraph containing the cursor.
1647         // (if this paragraph contains insets etc., rebreaking will
1648         // recursively descend)
1649         tm.redoParagraph(bottom_pit);
1650         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1651         if (pm.height() != old_height)
1652                 // Paragraph height has changed so we cannot proceed to
1653                 // the singlePar optimisation.
1654                 return false;
1655
1656         int y1 = pm.position() - pm.ascent();
1657         int y2 = pm.position() + pm.descent();
1658         d->metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1659                 SingleParUpdate, buftext.paragraphs().size());
1660         LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1661                 << "\ny1: " << y1
1662                 << " y2: " << y2
1663                 << " pit: " << bottom_pit
1664                 << " singlepar: 1");
1665         return true;
1666 }
1667
1668
1669 void BufferView::updateMetrics()
1670 {
1671         Text & buftext = buffer_.text();
1672         pit_type const npit = int(buftext.paragraphs().size());
1673
1674         if (d->anchor_ref_ > int(npit - 1)) {
1675                 d->anchor_ref_ = int(npit - 1);
1676                 d->offset_ref_ = 0;
1677         }
1678
1679         // Clear out the position cache in case of full screen redraw,
1680         d->coord_cache_.clear();
1681
1682         // Clear out paragraph metrics to avoid having invalid metrics
1683         // in the cache from paragraphs not relayouted below
1684         // The complete text metrics will be redone.
1685         d->text_metrics_.clear();
1686
1687         TextMetrics & tm = textMetrics(&buftext);
1688
1689         pit_type const pit = d->anchor_ref_;
1690         int pit1 = pit;
1691         int pit2 = pit;
1692
1693         // Rebreak anchor paragraph.
1694         tm.redoParagraph(pit);
1695
1696         // Take care of anchor offset if case a recentering is needed.
1697         updateOffsetRef();
1698
1699         int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1700
1701         // Redo paragraphs above anchor if necessary.
1702         int y1 = y0;
1703         while (y1 > 0 && pit1 > 0) {
1704                 y1 -= tm.parMetrics(pit1).ascent();
1705                 --pit1;
1706                 tm.redoParagraph(pit1);
1707                 y1 -= tm.parMetrics(pit1).descent();
1708         }
1709
1710         // Take care of ascent of first line
1711         y1 -= tm.parMetrics(pit1).ascent();
1712
1713         // Normalize anchor for next time
1714         d->anchor_ref_ = pit1;
1715         d->offset_ref_ = -y1;
1716
1717         // Grey at the beginning is ugly
1718         if (pit1 == 0 && y1 > 0) {
1719                 y0 -= y1;
1720                 y1 = 0;
1721                 d->anchor_ref_ = 0;
1722         }
1723
1724         // Redo paragraphs below the anchor if necessary.
1725         int y2 = y0;
1726         while (y2 < height_ && pit2 < int(npit) - 1) {
1727                 y2 += tm.parMetrics(pit2).descent();
1728                 ++pit2;
1729                 tm.redoParagraph(pit2);
1730                 y2 += tm.parMetrics(pit2).ascent();
1731         }
1732
1733         // Take care of descent of last line
1734         y2 += tm.parMetrics(pit2).descent();
1735
1736         LYXERR(Debug::PAINTING, BOOST_CURRENT_FUNCTION
1737                 << "\n y1: " << y1
1738                 << " y2: " << y2
1739                 << " pit1: " << pit1
1740                 << " pit2: " << pit2
1741                 << " npit: " << npit
1742                 << " singlepar: 0");
1743
1744         d->metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1745                 FullScreenUpdate, npit);
1746
1747         if (lyxerr.debugging(Debug::WORKAREA)) {
1748                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1749                 d->coord_cache_.dump();
1750         }
1751 }
1752
1753
1754 void BufferView::menuInsertLyXFile(string const & filenm)
1755 {
1756         BOOST_ASSERT(d->cursor_.inTexted());
1757         string filename = filenm;
1758
1759         if (filename.empty()) {
1760                 // Launch a file browser
1761                 // FIXME UNICODE
1762                 string initpath = lyxrc.document_path;
1763                 string const trypath = buffer_.filePath();
1764                 // If directory is writeable, use this as default.
1765                 if (FileName(trypath).isDirWritable())
1766                         initpath = trypath;
1767
1768                 // FIXME UNICODE
1769                 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1770                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1771                 dlg.setButton2(_("Examples|#E#e"),
1772                         from_utf8(addPath(package().system_support().absFilename(),
1773                         "examples")));
1774
1775                 FileDialog::Result result =
1776                         dlg.open(from_utf8(initpath),
1777                                      FileFilterList(_("LyX Documents (*.lyx)")),
1778                                      docstring());
1779
1780                 if (result.first == FileDialog::Later)
1781                         return;
1782
1783                 // FIXME UNICODE
1784                 filename = to_utf8(result.second);
1785
1786                 // check selected filename
1787                 if (filename.empty()) {
1788                         // emit message signal.
1789                         message(_("Canceled."));
1790                         return;
1791                 }
1792         }
1793
1794         // Get absolute path of file and add ".lyx"
1795         // to the filename if necessary
1796         filename = fileSearch(string(), filename, "lyx").absFilename();
1797
1798         docstring const disp_fn = makeDisplayPath(filename);
1799         // emit message signal.
1800         message(bformat(_("Inserting document %1$s..."), disp_fn));
1801
1802         docstring res;
1803         Buffer buf("", false);
1804         if (buf.loadLyXFile(FileName(filename))) {
1805                 ErrorList & el = buffer_.errorList("Parse");
1806                 // Copy the inserted document error list into the current buffer one.
1807                 el = buf.errorList("Parse");
1808                 buffer_.undo().recordUndo(d->cursor_);
1809                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1810                                              buf.params().getTextClassPtr(), el);
1811                 res = _("Document %1$s inserted.");
1812         } else {
1813                 res = _("Could not insert document %1$s");
1814         }
1815
1816         // emit message signal.
1817         message(bformat(res, disp_fn));
1818         buffer_.errors("Parse");
1819         updateMetrics();
1820 }
1821
1822
1823 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1824 {
1825         int x = 0;
1826         int y = 0;
1827         int lastw = 0;
1828
1829         // Addup contribution of nested insets, from inside to outside,
1830         // keeping the outer paragraph for a special handling below
1831         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1832                 CursorSlice const & sl = dit[i];
1833                 int xx = 0;
1834                 int yy = 0;
1835                 
1836                 // get relative position inside sl.inset()
1837                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1838                 
1839                 // Make relative position inside of the edited inset relative to sl.inset()
1840                 x += xx;
1841                 y += yy;
1842                 
1843                 // In case of an RTL inset, the edited inset will be positioned to the left
1844                 // of xx:yy
1845                 if (sl.text()) {
1846                         bool boundary_i = boundary && i + 1 == dit.depth();
1847                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1848                         if (rtl)
1849                                 x -= lastw;
1850                 }
1851
1852                 // remember width for the case that sl.inset() is positioned in an RTL inset
1853                 if (i && dit[i - 1].text()) {
1854                         // If this Inset is inside a Text Inset, retrieve the Dimension
1855                         // from the containing text instead of using Inset::dimension() which
1856                         // might not be implemented.
1857                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1858                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1859                         // to be rewritten in light of the new design.
1860                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1861                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1862                         lastw = dim.wid;
1863                 } else {
1864                         Dimension const dim = sl.inset().dimension(*this);
1865                         lastw = dim.wid;
1866                 }
1867                 
1868                 //lyxerr << "Cursor::getPos, i: "
1869                 // << i << " x: " << xx << " y: " << y << endl;
1870         }
1871
1872         // Add contribution of initial rows of outermost paragraph
1873         CursorSlice const & sl = dit[0];
1874         TextMetrics const & tm = textMetrics(sl.text());
1875         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1876         BOOST_ASSERT(!pm.rows().empty());
1877         y -= pm.rows()[0].ascent();
1878 #if 1
1879         // FIXME: document this mess
1880         size_t rend;
1881         if (sl.pos() > 0 && dit.depth() == 1) {
1882                 int pos = sl.pos();
1883                 if (pos && boundary)
1884                         --pos;
1885 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1886                 rend = pm.pos2row(pos);
1887         } else
1888                 rend = pm.pos2row(sl.pos());
1889 #else
1890         size_t rend = pm.pos2row(sl.pos());
1891 #endif
1892         for (size_t rit = 0; rit != rend; ++rit)
1893                 y += pm.rows()[rit].height();
1894         y += pm.rows()[rend].ascent();
1895         
1896         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1897         
1898         // Make relative position from the nested inset now bufferview absolute.
1899         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1900         x += xx;
1901         
1902         // In the RTL case place the nested inset at the left of the cursor in 
1903         // the outer paragraph
1904         bool boundary_1 = boundary && 1 == dit.depth();
1905         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1906         if (rtl)
1907                 x -= lastw;
1908         
1909         return Point(x, y);
1910 }
1911
1912
1913 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1914 {
1915         CursorSlice const & bot = dit.bottom();
1916         TextMetrics const & tm = textMetrics(bot.text());
1917         if (!tm.has(bot.pit()))
1918                 return Point(-1, -1);
1919
1920         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1921         p.y_ += tm.parMetrics(bot.pit()).position();
1922         return p;
1923 }
1924
1925
1926 void BufferView::draw(frontend::Painter & pain)
1927 {
1928         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1929         Text & text = buffer_.text();
1930         TextMetrics const & tm = d->text_metrics_[&text];
1931         int const y = d->metrics_info_.y1 
1932                 + tm.parMetrics(d->metrics_info_.p1).ascent();
1933         PainterInfo pi(this, pain);
1934
1935         switch (d->metrics_info_.update_strategy) {
1936
1937         case NoScreenUpdate:
1938                 // If no screen painting is actually needed, only some the different
1939                 // coordinates of insets and paragraphs needs to be updated.
1940                 pi.full_repaint = true;
1941                 pi.pain.setDrawingEnabled(false);
1942                 tm.draw(pi, 0, y);
1943                 break;
1944
1945         case SingleParUpdate:
1946                 // Only the current outermost paragraph will be redrawn.
1947                 pi.full_repaint = false;
1948                 tm.drawParagraph(pi, d->metrics_info_.p1, 0, y);
1949                 break;
1950
1951         case DecorationUpdate:
1952                 // FIXME: We should also distinguish DecorationUpdate to avoid text
1953                 // drawing if possible. This is not possible to do easily right now
1954                 // because of the single backing pixmap.
1955
1956         case FullScreenUpdate:
1957                 // The whole screen, including insets, will be refreshed.
1958                 pi.full_repaint = true;
1959
1960                 // Clear background (if not delegated to rows)
1961                 pain.fillRectangle(0, d->metrics_info_.y1, width_,
1962                         d->metrics_info_.y2 - d->metrics_info_.y1,
1963                         buffer_.inset().backgroundColor());
1964                 tm.draw(pi, 0, y);
1965
1966                 // and grey out above (should not happen later)
1967                 if (d->metrics_info_.y1 > 0)
1968                         pain.fillRectangle(0, 0, width_,
1969                                 d->metrics_info_.y1, Color_bottomarea);
1970
1971                 // and possibly grey out below
1972                 if (d->metrics_info_.y2 < height_)
1973                         pain.fillRectangle(0, d->metrics_info_.y2, width_,
1974                                 height_ - d->metrics_info_.y2, Color_bottomarea);
1975                 break;
1976         }
1977
1978         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
1979 }
1980
1981
1982 void BufferView::message(docstring const & msg)
1983 {
1984         if (d->gui_)
1985                 d->gui_->message(msg);
1986 }
1987
1988
1989 void BufferView::showDialog(std::string const & name)
1990 {
1991         if (d->gui_)
1992                 d->gui_->showDialog(name);
1993 }
1994
1995
1996 void BufferView::showDialogWithData(std::string const & name,
1997         std::string const & data)
1998 {
1999         if (d->gui_)
2000                 d->gui_->showDialogWithData(name, data);
2001 }
2002
2003
2004 void BufferView::showInsetDialog(std::string const & name,
2005         std::string const & data, Inset * inset)
2006 {
2007         if (d->gui_)
2008                 d->gui_->showInsetDialog(name, data, inset);
2009 }
2010
2011
2012 void BufferView::updateDialog(std::string const & name, std::string const & data)
2013 {
2014         if (d->gui_)
2015                 d->gui_->updateDialog(name, data);
2016 }
2017
2018
2019 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2020 {
2021         d->gui_ = gui;
2022 }
2023
2024
2025 // FIXME: Move this out of BufferView again
2026 docstring BufferView::contentsOfPlaintextFile(string const & f,
2027         bool asParagraph)
2028 {
2029         FileName fname(f);
2030
2031         if (fname.empty()) {
2032                 FileDialog dlg(_("Select file to insert"),
2033                                    ( asParagraph
2034                                      ? LFUN_FILE_INSERT_PLAINTEXT_PARA 
2035                                      : LFUN_FILE_INSERT_PLAINTEXT) );
2036
2037                 FileDialog::Result result =
2038                         dlg.open(from_utf8(buffer().filePath()),
2039                                      FileFilterList(), docstring());
2040
2041                 if (result.first == FileDialog::Later)
2042                         return docstring();
2043
2044                 fname = makeAbsPath(to_utf8(result.second));
2045
2046                 if (fname.empty())
2047                         return docstring();
2048         }
2049
2050         if (!fname.isReadable()) {
2051                 docstring const error = from_ascii(strerror(errno));
2052                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2053                 docstring const text =
2054                   bformat(_("Could not read the specified document\n"
2055                             "%1$s\ndue to the error: %2$s"), file, error);
2056                 Alert::error(_("Could not read file"), text);
2057                 return docstring();
2058         }
2059
2060         ifstream ifs(fname.toFilesystemEncoding().c_str());
2061         if (!ifs) {
2062                 docstring const error = from_ascii(strerror(errno));
2063                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2064                 docstring const text =
2065                   bformat(_("Could not open the specified document\n"
2066                             "%1$s\ndue to the error: %2$s"), file, error);
2067                 Alert::error(_("Could not open file"), text);
2068                 return docstring();
2069         }
2070
2071         ifs.unsetf(std::ios::skipws);
2072         istream_iterator<char> ii(ifs);
2073         istream_iterator<char> end;
2074 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2075         // We use this until the compilers get better...
2076         std::vector<char> tmp;
2077         copy(ii, end, back_inserter(tmp));
2078         string const tmpstr(tmp.begin(), tmp.end());
2079 #else
2080         // This is what we want to use and what we will use once the
2081         // compilers get good enough.
2082         //string tmpstr(ii, end); // yet a reason for using std::string
2083         // alternate approach to get the file into a string:
2084         string tmpstr;
2085         copy(ii, end, back_inserter(tmpstr));
2086 #endif
2087
2088         // FIXME UNICODE: We don't know the encoding of the file
2089         docstring file_content = from_utf8(tmpstr);
2090         if (file_content.empty()) {
2091                 Alert::error(_("Reading not UTF-8 encoded file"),
2092                              _("The file is not UTF-8 encoded.\n"
2093                                "It will be read as local 8Bit-encoded.\n"
2094                                "If this does not give the correct result\n"
2095                                "then please change the encoding of the file\n"
2096                                "to UTF-8 with a program other than LyX.\n"));
2097                 file_content = from_local8bit(tmpstr);
2098         }
2099
2100         return normalize_c(file_content);
2101 }
2102
2103
2104 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2105 {
2106         docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2107
2108         if (tmpstr.empty())
2109                 return;
2110
2111         Cursor & cur = cursor();
2112         cap::replaceSelection(cur);
2113         buffer_.undo().recordUndo(cur);
2114         if (asParagraph)
2115                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2116         else
2117                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2118 }
2119
2120 } // namespace lyx