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