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