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