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