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