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