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