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