]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
Fix bug 3142 (LyX crashes when using mouse wheel)
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
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 "bufferview_funcs.h"
24 #include "coordcache.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "dispatchresult.h"
28 #include "errorlist.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "funcrequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "intl.h"
35 #include "insetiterator.h"
36 #include "language.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
39 #include "lyx_main.h"
40 #include "lyxfind.h"
41 #include "lyxfunc.h"
42 #include "lyxlayout.h"
43 #include "lyxtext.h"
44 #include "lyxtextclass.h"
45 #include "lyxrc.h"
46 #include "session.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
51 #include "texrow.h"
52 #include "toc.h"
53 #include "undo.h"
54 #include "vspace.h"
55 #include "WordLangTuple.h"
56 #include "metricsinfo.h"
57
58 #include "insets/insetbibtex.h"
59 #include "insets/insetcommand.h" // ChangeRefs
60 #include "insets/insetref.h"
61 #include "insets/insettext.h"
62
63 #include "frontends/Alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Selection.h"
67
68 #include "graphics/Previews.h"
69
70 #include "support/convert.h"
71 #include "support/filefilterlist.h"
72 #include "support/filetools.h"
73 #include "support/package.h"
74 #include "support/types.h"
75
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
78
79 #include <functional>
80 #include <vector>
81
82
83 namespace lyx {
84
85 using support::addPath;
86 using support::bformat;
87 using support::FileFilterList;
88 using support::FileName;
89 using support::fileSearch;
90 using support::isDirWriteable;
91 using support::isFileReadable;
92 using support::makeDisplayPath;
93 using support::package;
94
95 using std::distance;
96 using std::endl;
97 using std::istringstream;
98 using std::make_pair;
99 using std::min;
100 using std::max;
101 using std::mem_fun_ref;
102 using std::string;
103 using std::vector;
104
105 namespace Alert = frontend::Alert;
106
107 namespace {
108
109 /// Return an inset of this class if it exists at the current cursor position
110 template <class T>
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
112 {
113         T * inset = 0;
114         DocIterator it = cur;
115         if (it.nextInset() &&
116             it.nextInset()->lyxCode() == code) {
117                 inset = static_cast<T*>(it.nextInset());
118         }
119         return inset;
120 }
121
122 } // anon namespace
123
124
125 BufferView::BufferView()
126         : width_(0), height_(0), buffer_(0), wh_(0),
127           cursor_(*this),
128           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129           intl_(new Intl), last_inset_(0)
130 {
131         xsel_cache_.set = false;
132         intl_->initKeyMapper(lyxrc.use_kbmap);
133 }
134
135
136 BufferView::~BufferView()
137 {
138 }
139
140
141 Buffer * BufferView::buffer() const
142 {
143         return buffer_;
144 }
145
146
147 void BufferView::setBuffer(Buffer * b)
148 {
149         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
150                             << "[ b = " << b << "]" << endl;
151
152         if (buffer_) {
153                 // Save the actual cursor position and anchor inside the
154                 // buffer so that it can be restored in case we rechange
155                 // to this buffer later on.
156                 buffer_->saveCursor(cursor_.selectionBegin(),
157                                     cursor_.selectionEnd());
158                 // update bookmark pit of the current buffer before switch
159                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
160                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
161                         if (buffer()->fileName() != bm.filename.absFilename())
162                                 continue;
163                         // if par_id or pit has been changed, reset par_pit and par_id
164                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
165                         pit_type new_pit;
166                         int new_id;
167                         boost::tie(new_pit, new_id) = moveToPosition(bm.par_pit, bm.par_id, bm.par_pos);
168                         if (bm.par_pit != new_pit || bm.par_id != new_id)
169                                 const_cast<BookmarksSection::Bookmark &>(bm).setPos(new_pit, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
173                         boost::tie(cursor_.pit(), cursor_.pos()) );
174         }
175
176         // If we're quitting lyx, don't bother updating stuff
177         if (quitting) {
178                 buffer_ = 0;
179                 return;
180         }
181
182         // If we are closing current buffer, switch to the first in
183         // buffer list.
184         if (!b) {
185                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
186                                     << " No Buffer!" << endl;
187                 // We are closing the buffer, use the first buffer as current
188                 buffer_ = theBufferList().first();
189         } else {
190                 // Set current buffer
191                 buffer_ = b;
192         }
193
194         // Reset old cursor
195         cursor_ = LCursor(*this);
196         anchor_ref_ = 0;
197         offset_ref_ = 0;
198
199         if (buffer_) {
200                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
201                                     << "Buffer addr: " << buffer_ << endl;
202                 cursor_.push(buffer_->inset());
203                 cursor_.resetAnchor();
204                 buffer_->text().setCurrentFont(cursor_);
205                 if (buffer_->getCursor().size() > 0 &&
206                     buffer_->getAnchor().size() > 0)
207                 {
208                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
209                         cursor_.resetAnchor();
210                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
211                         cursor_.setSelection();
212                         theSelection().haveSelection(cursor_.selection());
213                 }
214         }
215
216         if (buffer_)
217                 updateMetrics(false);    
218
219         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
220                 graphics::Previews::get().generateBufferPreviews(*buffer_);
221 }
222
223
224 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
225 {
226         // File already open?
227         if (theBufferList().exists(filename.absFilename())) {
228                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
229                 docstring text = bformat(_("The document %1$s is already "
230                                                      "loaded.\n\nDo you want to revert "
231                                                      "to the saved version?"), file);
232                 int const ret = Alert::prompt(_("Revert to saved document?"),
233                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
234
235                 if (ret != 0) {
236                         setBuffer(theBufferList().getBuffer(filename.absFilename()));
237                         return true;
238                 }
239                 // FIXME: should be LFUN_REVERT
240                 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
241                         return false;
242                 // Fall through to new load. (Asger)
243                 buffer_ = 0;
244         }
245
246         Buffer * b = 0;
247
248         if (isFileReadable(filename)) {
249                 b = theBufferList().newBuffer(filename.absFilename());
250                 if (!lyx::loadLyXFile(b, filename)) {
251                         theBufferList().release(b);
252                         return false;
253                 }
254         } else {
255                 docstring text = bformat(_("The document %1$s does not yet "
256                                                      "exist.\n\nDo you want to create "
257                                                      "a new document?"), from_utf8(filename.absFilename()));
258                 int const ret = Alert::prompt(_("Create new document?"),
259                          text, 0, 1, _("&Create"), _("Cancel"));
260
261                 if (ret == 0) {
262                         b = newFile(filename.absFilename(), string(), true);
263                         if (!b)
264                                 return false;
265                 } else
266                         return false;
267         }
268
269         setBuffer(b);
270         // Send the "errors" signal in case of parsing errors
271         b->errors("Parse");
272
273         // Update the labels and section numbering.
274         updateLabels(*buffer_);
275         // scroll to the position when the file was last closed
276         if (lyxrc.use_lastfilepos) {
277                 pit_type pit;
278                 pos_type pos;
279                 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
280                 // if successfully move to pit (returned par_id is not zero), update metrics
281                 if (moveToPosition(pit, 0, pos).get<1>()) {
282                         if (fitCursor())
283                                 updateMetrics(false);
284                 }
285         }
286
287         if (tolastfiles)
288                 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
289
290         return true;
291 }
292
293
294 void BufferView::resize()
295 {
296         if (!buffer_)
297                 return;
298
299         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
300
301         updateMetrics(false);
302         switchKeyMap();
303 }
304
305
306 bool BufferView::fitCursor()
307 {
308         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
309                 frontend::FontMetrics const & fm =
310                         theFontMetrics(cursor_.getFont());
311                 int const asc = fm.maxAscent();
312                 int const des = fm.maxDescent();
313                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
314                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
315                         return false;
316         }
317         center();
318         return true;
319 }
320
321
322 bool BufferView::multiParSel()
323 {
324         if (!cursor_.selection())
325                 return false;
326         bool ret = multiparsel_cache_;
327         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
328         // Either this, or previous selection spans paragraphs
329         return ret || multiparsel_cache_;
330 }
331
332
333 bool BufferView::update(Update::flags flags)
334 {
335         // last_inset_ points to the last visited inset. This pointer may become
336         // invalid because of keyboard editing. Since all such operations
337         // causes screen update(), I reset last_inset_ to avoid such a problem.
338         last_inset_ = 0;
339         // This is close to a hot-path.
340         if (lyxerr.debugging(Debug::DEBUG)) {
341                 lyxerr[Debug::DEBUG]
342                         << BOOST_CURRENT_FUNCTION
343                         << "[fitcursor = " << (flags & Update::FitCursor)
344                         << ", forceupdate = " << (flags & Update::Force)
345                         << ", singlepar = " << (flags & Update::SinglePar)
346                         << "]  buffer: " << buffer_ << endl;
347         }
348
349         // Check needed to survive LyX startup
350         if (!buffer_)
351                 return false;
352
353         if (lyxerr.debugging(Debug::WORKAREA)) {
354                 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
355         }
356
357         // Update macro store
358         buffer_->buildMacros();
359
360         // Now do the first drawing step if needed. This consists on updating
361         // the CoordCache in updateMetrics().
362         // The second drawing step is done in WorkArea::redraw() if needed.
363
364         // Case when no explicit update is requested.
365         if (!flags) {
366                 // no need to redraw anything.
367                 metrics_info_.update_strategy = NoScreenUpdate;
368                 return false;
369         }
370
371         if (flags == Update::Decoration) {
372                 metrics_info_.update_strategy = DecorationUpdate;
373                 return true;
374         }
375
376         if (flags == Update::FitCursor 
377                 || flags == (Update::Decoration | Update::FitCursor)) {
378                 bool const fit_cursor = fitCursor();
379                 // tell the frontend to update the screen if needed.
380                 if (fit_cursor) {
381                         updateMetrics(false);
382                         return true;
383                 }
384                 if (flags & Update::Decoration) {
385                         metrics_info_.update_strategy = DecorationUpdate;
386                         return true;
387                 }
388                 // no screen update is needed.
389                 metrics_info_.update_strategy = NoScreenUpdate;
390                 return false;
391         }
392
393         bool full_metrics = flags & Update::Force;
394         if (flags & Update::MultiParSel)
395                 full_metrics |= multiParSel();
396
397         bool const single_par = !full_metrics;
398         updateMetrics(single_par);
399
400         if (flags & Update::FitCursor && fitCursor())
401                 updateMetrics(false);
402
403         // tell the frontend to update the screen.
404         return true;
405 }
406
407
408 void BufferView::updateScrollbar()
409 {
410         if (!buffer_) {
411                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
412                                      << " no text in updateScrollbar" << endl;
413                 scrollbarParameters_.reset();
414                 return;
415         }
416
417         LyXText & t = buffer_->text();
418         TextMetrics & tm = text_metrics_[&t];
419
420         int const parsize = int(t.paragraphs().size() - 1);
421         if (anchor_ref_ >  parsize)  {
422                 anchor_ref_ = parsize;
423                 offset_ref_ = 0;
424         }
425
426         if (lyxerr.debugging(Debug::GUI)) {
427                 lyxerr[Debug::GUI]
428                         << BOOST_CURRENT_FUNCTION
429                         << " Updating scrollbar: height: " << t.paragraphs().size()
430                         << " curr par: " << cursor_.bottom().pit()
431                         << " default height " << defaultRowHeight() << endl;
432         }
433
434         // It would be better to fix the scrollbar to understand
435         // values in [0..1] and divide everything by wh
436
437         // estimated average paragraph height:
438         if (wh_ == 0)
439                 wh_ = height_ / 4;
440
441         int h = tm.parMetrics(anchor_ref_).height();
442
443         // Normalize anchor/offset (MV):
444         while (offset_ref_ > h && anchor_ref_ < parsize) {
445                 anchor_ref_++;
446                 offset_ref_ -= h;
447                 h = tm.parMetrics(anchor_ref_).height();
448         }
449         // Look at paragraph heights on-screen
450         int sumh = 0;
451         int nh = 0;
452         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
453                 if (sumh > height_)
454                         break;
455                 int const h2 = tm.parMetrics(pit).height();
456                 sumh += h2;
457                 nh++;
458         }
459
460         BOOST_ASSERT(nh);
461         int const hav = sumh / nh;
462         // More realistic average paragraph height
463         if (hav > wh_)
464                 wh_ = hav;
465
466         BOOST_ASSERT(h);
467         scrollbarParameters_.height = (parsize + 1) * wh_;
468         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
469         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
470 }
471
472
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
474 {
475         return scrollbarParameters_;
476 }
477
478
479 void BufferView::scrollDocView(int value)
480 {
481         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
482                            << "[ value = " << value << "]" << endl;
483
484         if (!buffer_)
485                 return;
486
487         LyXText & t = buffer_->text();
488         TextMetrics & tm = text_metrics_[&t];
489
490         float const bar = value / float(wh_ * t.paragraphs().size());
491
492         anchor_ref_ = int(bar * t.paragraphs().size());
493         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
494                 anchor_ref_ = int(t.paragraphs().size()) - 1;
495
496         tm.redoParagraph(anchor_ref_);
497         int const h = tm.parMetrics(anchor_ref_).height();
498         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
499         updateMetrics(false);
500 }
501
502
503 void BufferView::setCursorFromScrollbar()
504 {
505         if (!buffer)
506                 return;
507
508         LyXText & t = buffer_->text();
509
510         int const height = 2 * defaultRowHeight();
511         int const first = height;
512         int const last = height_ - height;
513         LCursor & cur = cursor_;
514
515         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
516
517         switch (st) {
518         case bv_funcs::CUR_ABOVE:
519                 // We reset the cursor because bv_funcs::status() does not
520                 // work when the cursor is within mathed.
521                 cur.reset(buffer_->inset());
522                 t.setCursorFromCoordinates(cur, 0, first);
523                 cur.clearSelection();
524                 break;
525         case bv_funcs::CUR_BELOW:
526                 // We reset the cursor because bv_funcs::status() does not
527                 // work when the cursor is within mathed.
528                 cur.reset(buffer_->inset());
529                 t.setCursorFromCoordinates(cur, 0, last);
530                 cur.clearSelection();
531                 break;
532         case bv_funcs::CUR_INSIDE:
533                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
534                 int const newy = min(last, max(y, first));
535                 if (y != newy) {
536                         cur.reset(buffer_->inset());
537                         t.setCursorFromCoordinates(cur, 0, newy);
538                 }
539         }
540 }
541
542
543 Change const BufferView::getCurrentChange() const
544 {
545         if (!cursor_.selection())
546                 return Change(Change::UNCHANGED);
547
548         DocIterator dit = cursor_.selectionBegin();
549         return dit.paragraph().lookupChange(dit.pos());
550 }
551
552
553 void BufferView::saveBookmark(bool persistent)
554 {
555         LyX::ref().session().bookmarks().save(
556                 FileName(buffer_->fileName()),
557                 cursor_.pit(),
558                 cursor_.paragraph().id(),
559                 cursor_.pos(),
560                 persistent
561         );
562         if (persistent)
563                 // emit message signal.
564                 message(_("Save bookmark"));
565 }
566
567
568 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
569 {
570         cursor_.clearSelection();
571
572         // if a valid par_id is given, try it first
573         if (par_id > 0) {
574                 ParIterator par = buffer_->getParFromID(par_id);
575                 if (par != buffer_->par_iterator_end()) {
576                         setCursor(makeDocIterator(par, min(par->size(), par_pos)));
577                         return boost::make_tuple(cursor_.pit(), par_id);
578                 }
579         }
580         // if par_id == 0, or searching through par_id failed
581         if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
582                 ParIterator it = buffer_->par_iterator_begin();
583                 ParIterator const end = buffer_->par_iterator_end();
584                 for (; it != end; ++it)
585                         if (it.pit() == par_pit) {
586                                 // restored pos may be bigger than it->size
587                                 setCursor(makeDocIterator(it, min(par_pos, it->size())));
588                                 return boost::make_tuple(par_pit, it->id());
589                         }
590         }
591         // both methods fail
592         return boost::make_tuple(pit_type(0), 0);
593 }
594
595
596 void BufferView::switchKeyMap()
597 {
598         if (!lyxrc.rtl_support)
599                 return;
600
601         if (getLyXText()->real_current_font.isRightToLeft()) {
602                 if (intl_->keymap == Intl::PRIMARY)
603                         intl_->keyMapSec();
604         } else {
605                 if (intl_->keymap == Intl::SECONDARY)
606                         intl_->keyMapPrim();
607         }
608 }
609
610
611 int BufferView::workWidth() const
612 {
613         return width_;
614 }
615
616
617 void BufferView::center()
618 {
619         CursorSlice & bot = cursor_.bottom();
620         TextMetrics & tm = text_metrics_[bot.text()];
621         pit_type const pit = bot.pit();
622         tm.redoParagraph(pit);
623         ParagraphMetrics const & pm = tm.parMetrics(pit);
624         anchor_ref_ = pit;
625         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
626                 + pm.ascent() - height_ / 2;
627 }
628
629
630 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
631 {
632         FuncStatus flag;
633
634         switch (cmd.action) {
635
636         case LFUN_UNDO:
637                 flag.enabled(!buffer_->undostack().empty());
638                 break;
639         case LFUN_REDO:
640                 flag.enabled(!buffer_->redostack().empty());
641                 break;
642         case LFUN_FILE_INSERT:
643         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
644         case LFUN_FILE_INSERT_PLAINTEXT:
645         case LFUN_BOOKMARK_SAVE:
646                 // FIXME: Actually, these LFUNS should be moved to LyXText
647                 flag.enabled(cursor_.inTexted());
648                 break;
649         case LFUN_FONT_STATE:
650         case LFUN_LABEL_INSERT:
651         case LFUN_PARAGRAPH_GOTO:
652         // FIXME handle non-trivially
653         case LFUN_OUTLINE_UP:
654         case LFUN_OUTLINE_DOWN:
655         case LFUN_OUTLINE_IN:
656         case LFUN_OUTLINE_OUT:
657         case LFUN_NOTE_NEXT:
658         case LFUN_REFERENCE_NEXT:
659         case LFUN_WORD_FIND:
660         case LFUN_WORD_REPLACE:
661         case LFUN_MARK_OFF:
662         case LFUN_MARK_ON:
663         case LFUN_MARK_TOGGLE:
664         case LFUN_SCREEN_RECENTER:
665         case LFUN_BIBTEX_DATABASE_ADD:
666         case LFUN_BIBTEX_DATABASE_DEL:
667         case LFUN_WORDS_COUNT:
668         case LFUN_NEXT_INSET_TOGGLE:
669                 flag.enabled(true);
670                 break;
671
672         case LFUN_LABEL_GOTO: {
673                 flag.enabled(!cmd.argument().empty()
674                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
675                 break;
676         }
677
678         case LFUN_CHANGES_TRACK:
679                 flag.enabled(true);
680                 flag.setOnOff(buffer_->params().trackChanges);
681                 break;
682
683         case LFUN_CHANGES_OUTPUT: {
684                 OutputParams runparams;
685                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
686                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
687                 flag.setOnOff(buffer_->params().outputChanges);
688                 break;
689         }
690
691         case LFUN_CHANGES_MERGE:
692         case LFUN_CHANGE_NEXT:
693         case LFUN_ALL_CHANGES_ACCEPT:
694         case LFUN_ALL_CHANGES_REJECT:
695                 // TODO: context-sensitive enabling of LFUNs
696                 // In principle, these command should only be enabled if there
697                 // is a change in the document. However, without proper
698                 // optimizations, this will inevitably result in poor performance.
699                 flag.enabled(buffer_);
700                 break;
701
702         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
703                 flag.setOnOff(buffer_->params().compressed);
704                 break;
705         }
706
707         default:
708                 flag.enabled(false);
709         }
710
711         return flag;
712 }
713
714
715 Update::flags BufferView::dispatch(FuncRequest const & cmd)
716 {
717         //lyxerr << BOOST_CURRENT_FUNCTION
718         //       << [ cmd = " << cmd << "]" << endl;
719
720         // Make sure that the cached BufferView is correct.
721         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
722                 << " action[" << cmd.action << ']'
723                 << " arg[" << to_utf8(cmd.argument()) << ']'
724                 << " x[" << cmd.x << ']'
725                 << " y[" << cmd.y << ']'
726                 << " button[" << cmd.button() << ']'
727                 << endl;
728
729         // FIXME: this should not be possible.
730         if (!buffer_)
731                 return Update::None;
732
733         LCursor & cur = cursor_;
734         // Default Update flags.
735         Update::flags updateFlags = Update::Force | Update::FitCursor;
736
737         switch (cmd.action) {
738
739         case LFUN_UNDO:
740                 cur.message(_("Undo"));
741                 cur.clearSelection();
742                 if (!textUndo(*this)) {
743                         cur.message(_("No further undo information"));
744                         updateFlags = Update::None;
745                 }
746                 switchKeyMap();
747                 break;
748
749         case LFUN_REDO:
750                 cur.message(_("Redo"));
751                 cur.clearSelection();
752                 if (!textRedo(*this)) {
753                         cur.message(_("No further redo information"));
754                         updateFlags = Update::None;
755                 }
756                 switchKeyMap();
757                 break;
758
759         case LFUN_FILE_INSERT:
760                 // FIXME UNICODE
761                 menuInsertLyXFile(to_utf8(cmd.argument()));
762                 break;
763
764         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
765                 // FIXME UNICODE
766                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
767                 break;
768
769         case LFUN_FILE_INSERT_PLAINTEXT:
770                 // FIXME UNICODE
771                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
772                 break;
773
774         case LFUN_FONT_STATE:
775                 cur.message(cur.currentState());
776                 break;
777
778         case LFUN_BOOKMARK_SAVE:
779                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
780                 break;
781
782         case LFUN_LABEL_GOTO: {
783                 docstring label = cmd.argument();
784                 if (label.empty()) {
785                         InsetRef * inset =
786                                 getInsetByCode<InsetRef>(cursor_,
787                                                          InsetBase::REF_CODE);
788                         if (inset) {
789                                 label = inset->getParam("reference");
790                                 // persistent=false: use temp_bookmark
791                                 saveBookmark(false);
792                         }
793                 }
794
795                 if (!label.empty())
796                         gotoLabel(label);
797                 break;
798         }
799
800         case LFUN_PARAGRAPH_GOTO: {
801                 int const id = convert<int>(to_utf8(cmd.argument()));
802                 int i = 0;
803                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
804                         ParIterator par = b->getParFromID(id);
805                         if (par == b->par_iterator_end()) {
806                                 lyxerr[Debug::INFO]
807                                         << "No matching paragraph found! ["
808                                         << id << "]." << endl;
809                         } else {
810                                 lyxerr[Debug::INFO]
811                                         << "Paragraph " << par->id()
812                                         << " found in buffer `"
813                                         << b->fileName() << "'." << endl;
814
815                                 if (b == buffer_) {
816                                         // Set the cursor
817                                         setCursor(makeDocIterator(par, 0));
818                                         switchKeyMap();
819                                 } else {
820                                         // Switch to other buffer view and resend cmd
821                                         theLyXFunc().dispatch(FuncRequest(
822                                                 LFUN_BUFFER_SWITCH, b->fileName()));
823                                         theLyXFunc().dispatch(cmd);
824                                         updateFlags = Update::None;
825                                 }
826                                 break;
827                         }
828                         ++i;
829                 }
830                 break;
831         }
832
833         case LFUN_OUTLINE_UP:
834                 toc::outline(toc::Up, cursor_);
835                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
836                 updateLabels(*buffer_);
837                 break;
838         case LFUN_OUTLINE_DOWN:
839                 toc::outline(toc::Down, cursor_);
840                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
841                 updateLabels(*buffer_);
842                 break;
843         case LFUN_OUTLINE_IN:
844                 toc::outline(toc::In, cursor_);
845                 updateLabels(*buffer_);
846                 break;
847         case LFUN_OUTLINE_OUT:
848                 toc::outline(toc::Out, cursor_);
849                 updateLabels(*buffer_);
850                 break;
851
852         case LFUN_NOTE_NEXT:
853                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
854                 break;
855
856         case LFUN_REFERENCE_NEXT: {
857                 vector<InsetBase_code> tmp;
858                 tmp.push_back(InsetBase::LABEL_CODE);
859                 tmp.push_back(InsetBase::REF_CODE);
860                 bv_funcs::gotoInset(this, tmp, true);
861                 break;
862         }
863
864         case LFUN_CHANGES_TRACK:
865                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
866                 break;
867
868         case LFUN_CHANGES_OUTPUT:
869                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
870                 break;
871
872         case LFUN_CHANGE_NEXT:
873                 findNextChange(this);
874                 break;
875
876         case LFUN_CHANGES_MERGE:
877                 if (findNextChange(this))
878                         showDialog("changes");
879                 break;
880
881         case LFUN_ALL_CHANGES_ACCEPT: {
882                 cursor_.reset(buffer_->inset());
883 #ifdef WITH_WARNINGS
884 #warning FIXME changes
885 #endif
886                 while (findNextChange(this))
887                         getLyXText()->acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
888                 break;
889         }
890
891         case LFUN_ALL_CHANGES_REJECT: {
892                 cursor_.reset(buffer_->inset());
893 #ifdef WITH_WARNINGS
894 #warning FIXME changes
895 #endif
896                 while (findNextChange(this))
897                         getLyXText()->acceptOrRejectChanges(cursor_, LyXText::REJECT);
898                 break;
899         }
900
901         case LFUN_WORD_FIND:
902                 find(this, cmd);
903                 break;
904
905         case LFUN_WORD_REPLACE:
906                 replace(this, cmd);
907                 break;
908
909         case LFUN_MARK_OFF:
910                 cur.clearSelection();
911                 cur.resetAnchor();
912                 cur.message(from_utf8(N_("Mark off")));
913                 break;
914
915         case LFUN_MARK_ON:
916                 cur.clearSelection();
917                 cur.mark() = true;
918                 cur.resetAnchor();
919                 cur.message(from_utf8(N_("Mark on")));
920                 break;
921
922         case LFUN_MARK_TOGGLE:
923                 cur.clearSelection();
924                 if (cur.mark()) {
925                         cur.mark() = false;
926                         cur.message(from_utf8(N_("Mark removed")));
927                 } else {
928                         cur.mark() = true;
929                         cur.message(from_utf8(N_("Mark set")));
930                 }
931                 cur.resetAnchor();
932                 break;
933
934         case LFUN_SCREEN_RECENTER:
935                 center();
936                 break;
937
938         case LFUN_BIBTEX_DATABASE_ADD: {
939                 LCursor tmpcur = cursor_;
940                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
941                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
942                                                 InsetBase::BIBTEX_CODE);
943                 if (inset) {
944                         if (inset->addDatabase(to_utf8(cmd.argument())))
945                                 buffer_->updateBibfilesCache();
946                 }
947                 break;
948         }
949
950         case LFUN_BIBTEX_DATABASE_DEL: {
951                 LCursor tmpcur = cursor_;
952                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
953                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
954                                                 InsetBase::BIBTEX_CODE);
955                 if (inset) {
956                         if (inset->delDatabase(to_utf8(cmd.argument())))
957                                 buffer_->updateBibfilesCache();
958                 }
959                 break;
960         }
961
962         case LFUN_WORDS_COUNT: {
963                 DocIterator from, to;
964                 if (cur.selection()) {
965                         from = cur.selectionBegin();
966                         to = cur.selectionEnd();
967                 } else {
968                         from = doc_iterator_begin(buffer_->inset());
969                         to = doc_iterator_end(buffer_->inset());
970                 }
971                 int const count = countWords(from, to);
972                 docstring message;
973                 if (count != 1) {
974                         if (cur.selection())
975                                 message = bformat(_("%1$d words in selection."),
976                                           count);
977                                 else
978                                         message = bformat(_("%1$d words in document."),
979                                                           count);
980                 }
981                 else {
982                         if (cur.selection())
983                                 message = _("One word in selection.");
984                         else
985                                 message = _("One word in document.");
986                 }
987
988                 Alert::information(_("Count words"), message);
989         }
990                 break;
991
992         case LFUN_BUFFER_TOGGLE_COMPRESSION:
993                 // turn compression on/off
994                 buffer_->params().compressed = !buffer_->params().compressed;
995                 break;
996
997         case LFUN_NEXT_INSET_TOGGLE: {
998                 // this is the real function we want to invoke
999                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1000                 // if there is an inset at cursor, see whether it
1001                 // wants to toggle.
1002                 InsetBase * inset = cur.nextInset();
1003                 if (inset && inset->isActive()) {
1004                         LCursor tmpcur = cur;
1005                         tmpcur.pushLeft(*inset);
1006                         inset->dispatch(tmpcur, tmpcmd);
1007                         if (tmpcur.result().dispatched()) {
1008                                 cur.dispatched();
1009                         }
1010                 }
1011                 // if it did not work, try the underlying inset.
1012                 if (!cur.result().dispatched())
1013                         cur.dispatch(tmpcmd);
1014
1015                 if (cur.result().dispatched())
1016                         cur.clearSelection();
1017
1018                 break;
1019         }
1020
1021         default:
1022                 updateFlags = Update::None;
1023         }
1024
1025         return updateFlags;
1026 }
1027
1028
1029 docstring const BufferView::requestSelection()
1030 {
1031         if (!buffer_)
1032                 return docstring();
1033
1034         LCursor & cur = cursor_;
1035
1036         if (!cur.selection()) {
1037                 xsel_cache_.set = false;
1038                 return docstring();
1039         }
1040
1041         if (!xsel_cache_.set ||
1042             cur.top() != xsel_cache_.cursor ||
1043             cur.anchor_.top() != xsel_cache_.anchor)
1044         {
1045                 xsel_cache_.cursor = cur.top();
1046                 xsel_cache_.anchor = cur.anchor_.top();
1047                 xsel_cache_.set = cur.selection();
1048                 return cur.selectionAsString(false);
1049         }
1050         return docstring();
1051 }
1052
1053
1054 void BufferView::clearSelection()
1055 {
1056         if (buffer_) {
1057                 cursor_.clearSelection();
1058                 xsel_cache_.set = false;
1059                 // The buffer did not really change, but this causes the
1060                 // redraw we need because we cleared the selection above.
1061                 buffer_->changed();
1062         }
1063 }
1064
1065
1066 void BufferView::workAreaResize(int width, int height)
1067 {
1068         // Update from work area
1069         width_ = width;
1070         height_ = height;
1071
1072         // The complete text metrics will be redone.
1073         text_metrics_.clear();
1074
1075         if (buffer_)
1076                 resize();
1077 }
1078
1079
1080 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1081 {
1082         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1083
1084         // This is only called for mouse related events including
1085         // LFUN_FILE_OPEN generated by drag-and-drop.
1086         FuncRequest cmd = cmd0;
1087
1088         // E.g. Qt mouse press when no buffer
1089         if (!buffer_)
1090                 return false;
1091
1092         LCursor cur(*this);
1093         cur.push(buffer_->inset());
1094         cur.selection() = cursor_.selection();
1095
1096         // Either the inset under the cursor or the
1097         // surrounding LyXText will handle this event.
1098
1099         // Build temporary cursor.
1100         cmd.y = min(max(cmd.y, -1), height_);
1101         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1102
1103         //lyxerr << BOOST_CURRENT_FUNCTION
1104         //       << " * hit inset at tip: " << inset << endl;
1105         //lyxerr << BOOST_CURRENT_FUNCTION
1106         //       << " * created temp cursor:" << cur << endl;
1107
1108         // NOTE: editXY returns the top level inset of nested insets. If you happen
1109         // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1110         // footnote inset, again inset=0), that inset will not be redrawn.
1111         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1112                 bool need_redraw = false;
1113                 
1114                 if (inset != last_inset_) {
1115                         if (last_inset_)
1116                                 need_redraw |= last_inset_->setMouseHover(false);
1117                         if (inset)
1118                                 need_redraw |= inset->setMouseHover(true);
1119                         last_inset_ = inset;
1120                 }
1121
1122                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1123                 // not expose the button for redraw. We adjust here the metrics dimension
1124                 // to enable a full redraw.
1125                 // FIXME: It is possible to redraw only the area around the button!
1126                 if (need_redraw 
1127                         && metrics_info_.update_strategy == SingleParUpdate) {
1128                         // FIXME: It should be possible to redraw only the area around 
1129                         // the button by doing this:
1130                         //
1131                         //metrics_info_.singlepar = false;
1132                         //metrics_info_.y1 = ymin of button;
1133                         //metrics_info_.y2 = ymax of button;
1134                         //
1135                         // Unfortunately, rowpainter.C:paintText() does not distinguish
1136                         // between background updates and text updates. So we use the hammer
1137                         // solution for now. We could also avoid the updateMetrics() below
1138                         // by using the first and last pit of the CoordCache. Have a look
1139                         // at LyXText::getPitNearY() to see what I mean.
1140                         //
1141                         //metrics_info_.pit1 = first pit of CoordCache;
1142                         //metrics_info_.pit2 = last pit of CoordCache;
1143                         //metrics_info_.singlepar = false;
1144                         //metrics_info_.y1 = 0;
1145                         //metrics_info_.y2 = height_;
1146                         //
1147                         updateMetrics(false);
1148                 }
1149
1150                 // This event (moving without mouse click) is not passed further.
1151                 // This should be changed if it is further utilized.
1152                 return need_redraw;
1153         }
1154
1155         // Put anchor at the same position.
1156         cur.resetAnchor();
1157
1158         // Try to dispatch to an non-editable inset near this position
1159         // via the temp cursor. If the inset wishes to change the real
1160         // cursor it has to do so explicitly by using
1161         //  cur.bv().cursor() = cur;  (or similar)
1162         if (inset) {
1163                 inset->dispatch(cur, cmd);
1164         }
1165
1166         // Now dispatch to the temporary cursor. If the real cursor should
1167         // be modified, the inset's dispatch has to do so explicitly.
1168         if (!cur.result().dispatched())
1169                 cur.dispatch(cmd);
1170
1171         // Redraw if requested and necessary.
1172         if (cur.result().dispatched() && cur.result().update())
1173                 return update(cur.result().update());
1174
1175         return false;
1176 }
1177
1178
1179 void BufferView::scroll(int /*lines*/)
1180 {
1181 //      if (!buffer_)
1182 //              return;
1183 //
1184 //      LyXText const * t = &buffer_->text();
1185 //      int const line_height = defaultRowHeight();
1186 //
1187 //      // The new absolute coordinate
1188 //      int new_top_y = top_y() + lines * line_height;
1189 //
1190 //      // Restrict to a valid value
1191 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1192 //      new_top_y = std::max(0, new_top_y);
1193 //
1194 //      scrollDocView(new_top_y);
1195 //
1196 }
1197
1198
1199 void BufferView::setCursorFromRow(int row)
1200 {
1201         int tmpid = -1;
1202         int tmppos = -1;
1203
1204         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1205
1206         if (tmpid == -1)
1207                 buffer_->text().setCursor(cursor_, 0, 0);
1208         else
1209                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1210 }
1211
1212
1213 void BufferView::gotoLabel(docstring const & label)
1214 {
1215         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1216                 vector<docstring> labels;
1217                 it->getLabelList(*buffer_, labels);
1218                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1219                         setCursor(it);
1220                         update();
1221                         return;
1222                 }
1223         }
1224 }
1225
1226
1227 LyXText * BufferView::getLyXText()
1228 {
1229         LyXText * text = cursor_.innerText();
1230         BOOST_ASSERT(text);
1231         return text;
1232 }
1233
1234
1235 LyXText const * BufferView::getLyXText() const
1236 {
1237         LyXText const * text = cursor_.innerText();
1238         BOOST_ASSERT(text);
1239         return text;
1240 }
1241
1242
1243 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1244 {
1245         return const_cast<BufferView *>(this)->textMetrics(t);
1246 }
1247
1248
1249 TextMetrics & BufferView::textMetrics(LyXText const * t)
1250 {
1251         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1252         if (tmc_it == text_metrics_.end()) {
1253                 tmc_it = text_metrics_.insert(
1254                         make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1255         }       
1256         return tmc_it->second;
1257 }
1258
1259
1260 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1261                 pit_type pit) const
1262 {
1263         return textMetrics(t).parMetrics(pit);
1264 }
1265
1266
1267 int BufferView::workHeight() const
1268 {
1269         return height_;
1270 }
1271
1272
1273 void BufferView::setCursor(DocIterator const & dit)
1274 {
1275         size_t const n = dit.depth();
1276         for (size_t i = 0; i < n; ++i)
1277                 dit[i].inset().edit(cursor_, true);
1278
1279         cursor_.setCursor(dit);
1280         cursor_.selection() = false;
1281 }
1282
1283
1284 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1285 {
1286         // Would be wrong to delete anything if we have a selection.
1287         if (cur.selection())
1288                 return false;
1289
1290         bool need_anchor_change = false;
1291         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1292                 need_anchor_change);
1293
1294         if (need_anchor_change)
1295                 cur.resetAnchor();
1296         
1297         if (!changed)
1298                 return false;
1299
1300         updateMetrics(false);
1301         buffer_->changed();
1302         return true;
1303 }
1304
1305
1306 bool BufferView::mouseSetCursor(LCursor & cur)
1307 {
1308         BOOST_ASSERT(&cur.bv() == this);
1309
1310         // Has the cursor just left the inset?
1311         bool badcursor = false;
1312         if (&cursor_.inset() != &cur.inset())
1313                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1314
1315         // do the dEPM magic if needed
1316         // FIXME: move this to InsetText::notifyCursorLeaves?
1317         bool update = false;
1318         if (!badcursor && cursor_.inTexted())
1319                 checkDepm(cur, cursor_);
1320
1321         // if the cursor was in an empty script inset and the new
1322         // position is in the nucleus of the inset, notifyCursorLeaves
1323         // will kill the script inset itself. So we check all the
1324         // elements of the cursor to make sure that they are correct.
1325         // For an example, see bug 2933: 
1326         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1327         // The code below could maybe be moved to a DocIterator method.
1328         //lyxerr << "cur before " << cur <<std::endl;
1329         DocIterator dit(cur.inset());
1330         dit.push_back(cur.bottom());
1331         size_t i = 1;
1332         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1333                 dit.push_back(cur[i]);
1334                 ++i;
1335         }
1336         //lyxerr << "5 cur after" << dit <<std::endl;
1337
1338         cursor_.setCursor(dit);
1339         cursor_.clearSelection();
1340         // remember new position.
1341         cursor_.setTargetX();
1342         finishUndo();
1343         return update;
1344 }
1345
1346
1347 void BufferView::putSelectionAt(DocIterator const & cur,
1348                                 int length, bool backwards)
1349 {
1350         cursor_.clearSelection();
1351
1352         setCursor(cur);
1353
1354         if (length) {
1355                 if (backwards) {
1356                         cursor_.pos() += length;
1357                         cursor_.setSelection(cursor_, -length);
1358                 } else
1359                         cursor_.setSelection(cursor_, length);
1360                 theSelection().haveSelection(cursor_.selection());
1361         }
1362 }
1363
1364
1365 LCursor & BufferView::cursor()
1366 {
1367         return cursor_;
1368 }
1369
1370
1371 LCursor const & BufferView::cursor() const
1372 {
1373         return cursor_;
1374 }
1375
1376
1377 pit_type BufferView::anchor_ref() const
1378 {
1379         return anchor_ref_;
1380 }
1381
1382
1383 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1384 {
1385         return metrics_info_;
1386 }
1387
1388
1389 // FIXME: We should split-up updateMetrics() for the singlepar case.
1390 void BufferView::updateMetrics(bool singlepar)
1391 {
1392         LyXText & buftext = buffer_->text();
1393         TextMetrics & tm = textMetrics(&buftext);
1394         pit_type size = int(buftext.paragraphs().size());
1395
1396         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1397                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1398                 offset_ref_ = 0;
1399         }
1400         
1401         // If the paragraph metrics has changed, we can not
1402         // use the singlepar optimisation.
1403         if (singlepar
1404                 // In Single Paragraph mode, rebreak only
1405                 // the (main text, not inset!) paragraph containing the cursor.
1406                 // (if this paragraph contains insets etc., rebreaking will
1407                 // recursively descend)
1408                 && tm.redoParagraph(cursor_.bottom().pit()))
1409                 singlepar = false;
1410
1411         pit_type const pit = anchor_ref_;
1412         int pit1 = pit;
1413         int pit2 = pit;
1414         size_t const npit = buftext.paragraphs().size();
1415
1416         // Rebreak anchor paragraph.
1417         if (!singlepar)
1418                 tm.redoParagraph(pit);
1419         
1420         // Clear out the position cache in case of full screen redraw.
1421         if (!singlepar)
1422                 coord_cache_.clear();
1423
1424         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1425
1426         // Redo paragraphs above anchor if necessary.
1427         int y1 = y0;
1428         while (y1 > 0 && pit1 > 0) {
1429                 y1 -= tm.parMetrics(pit1).ascent();
1430                 --pit1;
1431                 if (!singlepar)
1432                         tm.redoParagraph(pit1);
1433                 y1 -= tm.parMetrics(pit1).descent();
1434         }
1435
1436
1437         // Take care of ascent of first line
1438         y1 -= tm.parMetrics(pit1).ascent();
1439
1440         // Normalize anchor for next time
1441         anchor_ref_ = pit1;
1442         offset_ref_ = -y1;
1443
1444         // Grey at the beginning is ugly
1445         if (pit1 == 0 && y1 > 0) {
1446                 y0 -= y1;
1447                 y1 = 0;
1448                 anchor_ref_ = 0;
1449         }
1450
1451         // Redo paragraphs below the anchor if necessary.
1452         int y2 = y0;
1453         while (y2 < height_ && pit2 < int(npit) - 1) {
1454                 y2 += tm.parMetrics(pit2).descent();
1455                 ++pit2;
1456                 if (!singlepar)
1457                         tm.redoParagraph(pit2);
1458                 y2 += tm.parMetrics(pit2).ascent();
1459         }
1460
1461         // Take care of descent of last line
1462         y2 += tm.parMetrics(pit2).descent();
1463
1464         // The coordinates of all these paragraphs are correct, cache them
1465         int y = y1;
1466         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1467         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1468                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1469                 y += pm.ascent();
1470                 parPos[pit] = Point(0, y);
1471                 if (singlepar && pit == cursor_.bottom().pit()) {
1472                         // In Single Paragraph mode, collect here the
1473                         // y1 and y2 of the (one) paragraph the cursor is in
1474                         y1 = y - pm.ascent();
1475                         y2 = y + pm.descent();
1476                 }
1477                 y += pm.descent();
1478         }
1479
1480         if (singlepar) {
1481                 // collect cursor paragraph iter bounds
1482                 pit1 = cursor_.bottom().pit();
1483                 pit2 = cursor_.bottom().pit();
1484         }
1485
1486         lyxerr[Debug::DEBUG]
1487                 << BOOST_CURRENT_FUNCTION
1488                 << " y1: " << y1
1489                 << " y2: " << y2
1490                 << " pit1: " << pit1
1491                 << " pit2: " << pit2
1492                 << " npit: " << npit
1493                 << " singlepar: " << singlepar
1494                 << "size: " << size
1495                 << endl;
1496
1497         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
1498                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1499
1500         if (lyxerr.debugging(Debug::WORKAREA)) {
1501                 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1502                 coord_cache_.dump();
1503         }
1504 }
1505
1506
1507 void BufferView::menuInsertLyXFile(string const & filenm)
1508 {
1509         BOOST_ASSERT(cursor_.inTexted());
1510         string filename = filenm;
1511
1512         if (filename.empty()) {
1513                 // Launch a file browser
1514                 // FIXME UNICODE
1515                 string initpath = lyxrc.document_path;
1516
1517                 if (buffer_) {
1518                         string const trypath = buffer_->filePath();
1519                         // If directory is writeable, use this as default.
1520                         if (isDirWriteable(FileName(trypath)))
1521                                 initpath = trypath;
1522                 }
1523
1524                 // FIXME UNICODE
1525                 FileDialog fileDlg(_("Select LyX document to insert"),
1526                         LFUN_FILE_INSERT,
1527                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1528                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1529
1530                 FileDialog::Result result =
1531                         fileDlg.open(from_utf8(initpath),
1532                                      FileFilterList(_("LyX Documents (*.lyx)")),
1533                                      docstring());
1534
1535                 if (result.first == FileDialog::Later)
1536                         return;
1537
1538                 // FIXME UNICODE
1539                 filename = to_utf8(result.second);
1540
1541                 // check selected filename
1542                 if (filename.empty()) {
1543                         // emit message signal.
1544                         message(_("Canceled."));
1545                         return;
1546                 }
1547         }
1548
1549         // Get absolute path of file and add ".lyx"
1550         // to the filename if necessary
1551         filename = fileSearch(string(), filename, "lyx").absFilename();
1552
1553         docstring const disp_fn = makeDisplayPath(filename);
1554         // emit message signal.
1555         message(bformat(_("Inserting document %1$s..."), disp_fn));
1556
1557         docstring res;
1558         Buffer buf("", false);
1559         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1560                 ErrorList & el = buffer_->errorList("Parse");
1561                 // Copy the inserted document error list into the current buffer one.
1562                 el = buf.errorList("Parse");
1563                 recordUndo(cursor_);
1564                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1565                                              buf.params().textclass, el);
1566                 res = _("Document %1$s inserted.");
1567         } else
1568                 res = _("Could not insert document %1$s");
1569
1570         // emit message signal.
1571         message(bformat(res, disp_fn));
1572         buffer_->errors("Parse");
1573         resize();
1574 }
1575
1576 } // namespace lyx