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