]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
acd74c38f083aeb6f52163419946a5911266d72b
[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         LyXText & t = buffer_->text();
506
507         int const height = 2 * defaultRowHeight();
508         int const first = height;
509         int const last = height_ - height;
510         LCursor & cur = cursor_;
511
512         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
513
514         switch (st) {
515         case bv_funcs::CUR_ABOVE:
516                 // We reset the cursor because bv_funcs::status() does not
517                 // work when the cursor is within mathed.
518                 cur.reset(buffer_->inset());
519                 t.setCursorFromCoordinates(cur, 0, first);
520                 cur.clearSelection();
521                 break;
522         case bv_funcs::CUR_BELOW:
523                 // We reset the cursor because bv_funcs::status() does not
524                 // work when the cursor is within mathed.
525                 cur.reset(buffer_->inset());
526                 t.setCursorFromCoordinates(cur, 0, last);
527                 cur.clearSelection();
528                 break;
529         case bv_funcs::CUR_INSIDE:
530                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
531                 int const newy = min(last, max(y, first));
532                 if (y != newy) {
533                         cur.reset(buffer_->inset());
534                         t.setCursorFromCoordinates(cur, 0, newy);
535                 }
536         }
537 }
538
539
540 Change const BufferView::getCurrentChange() const
541 {
542         if (!cursor_.selection())
543                 return Change(Change::UNCHANGED);
544
545         DocIterator dit = cursor_.selectionBegin();
546         return dit.paragraph().lookupChange(dit.pos());
547 }
548
549
550 void BufferView::saveBookmark(bool persistent)
551 {
552         LyX::ref().session().bookmarks().save(
553                 FileName(buffer_->fileName()),
554                 cursor_.pit(),
555                 cursor_.paragraph().id(),
556                 cursor_.pos(),
557                 persistent
558         );
559         if (persistent)
560                 // emit message signal.
561                 message(_("Save bookmark"));
562 }
563
564
565 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
566 {
567         cursor_.clearSelection();
568
569         // if a valid par_id is given, try it first
570         if (par_id > 0) {
571                 ParIterator par = buffer_->getParFromID(par_id);
572                 if (par != buffer_->par_iterator_end()) {
573                         setCursor(makeDocIterator(par, min(par->size(), par_pos)));
574                         return boost::make_tuple(cursor_.pit(), par_id);
575                 }
576         }
577         // if par_id == 0, or searching through par_id failed
578         if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
579                 ParIterator it = buffer_->par_iterator_begin();
580                 ParIterator const end = buffer_->par_iterator_end();
581                 for (; it != end; ++it)
582                         if (it.pit() == par_pit) {
583                                 // restored pos may be bigger than it->size
584                                 setCursor(makeDocIterator(it, min(par_pos, it->size())));
585                                 return boost::make_tuple(par_pit, it->id());
586                         }
587         }
588         // both methods fail
589         return boost::make_tuple(pit_type(0), 0);
590 }
591
592
593 void BufferView::switchKeyMap()
594 {
595         if (!lyxrc.rtl_support)
596                 return;
597
598         if (getLyXText()->real_current_font.isRightToLeft()) {
599                 if (intl_->keymap == Intl::PRIMARY)
600                         intl_->keyMapSec();
601         } else {
602                 if (intl_->keymap == Intl::SECONDARY)
603                         intl_->keyMapPrim();
604         }
605 }
606
607
608 int BufferView::workWidth() const
609 {
610         return width_;
611 }
612
613
614 void BufferView::center()
615 {
616         CursorSlice & bot = cursor_.bottom();
617         TextMetrics & tm = text_metrics_[bot.text()];
618         pit_type const pit = bot.pit();
619         tm.redoParagraph(pit);
620         ParagraphMetrics const & pm = tm.parMetrics(pit);
621         anchor_ref_ = pit;
622         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
623                 + pm.ascent() - height_ / 2;
624 }
625
626
627 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
628 {
629         FuncStatus flag;
630
631         switch (cmd.action) {
632
633         case LFUN_UNDO:
634                 flag.enabled(!buffer_->undostack().empty());
635                 break;
636         case LFUN_REDO:
637                 flag.enabled(!buffer_->redostack().empty());
638                 break;
639         case LFUN_FILE_INSERT:
640         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
641         case LFUN_FILE_INSERT_PLAINTEXT:
642         case LFUN_BOOKMARK_SAVE:
643                 // FIXME: Actually, these LFUNS should be moved to LyXText
644                 flag.enabled(cursor_.inTexted());
645                 break;
646         case LFUN_FONT_STATE:
647         case LFUN_LABEL_INSERT:
648         case LFUN_PARAGRAPH_GOTO:
649         // FIXME handle non-trivially
650         case LFUN_OUTLINE_UP:
651         case LFUN_OUTLINE_DOWN:
652         case LFUN_OUTLINE_IN:
653         case LFUN_OUTLINE_OUT:
654         case LFUN_NOTE_NEXT:
655         case LFUN_REFERENCE_NEXT:
656         case LFUN_WORD_FIND:
657         case LFUN_WORD_REPLACE:
658         case LFUN_MARK_OFF:
659         case LFUN_MARK_ON:
660         case LFUN_MARK_TOGGLE:
661         case LFUN_SCREEN_RECENTER:
662         case LFUN_BIBTEX_DATABASE_ADD:
663         case LFUN_BIBTEX_DATABASE_DEL:
664         case LFUN_WORDS_COUNT:
665         case LFUN_NEXT_INSET_TOGGLE:
666                 flag.enabled(true);
667                 break;
668
669         case LFUN_LABEL_GOTO: {
670                 flag.enabled(!cmd.argument().empty()
671                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
672                 break;
673         }
674
675         case LFUN_CHANGES_TRACK:
676                 flag.enabled(true);
677                 flag.setOnOff(buffer_->params().trackChanges);
678                 break;
679
680         case LFUN_CHANGES_OUTPUT: {
681                 OutputParams runparams;
682                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
683                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
684                 flag.setOnOff(buffer_->params().outputChanges);
685                 break;
686         }
687
688         case LFUN_CHANGES_MERGE:
689         case LFUN_CHANGE_NEXT:
690         case LFUN_ALL_CHANGES_ACCEPT:
691         case LFUN_ALL_CHANGES_REJECT:
692                 // TODO: context-sensitive enabling of LFUNs
693                 // In principle, these command should only be enabled if there
694                 // is a change in the document. However, without proper
695                 // optimizations, this will inevitably result in poor performance.
696                 flag.enabled(buffer_);
697                 break;
698
699         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
700                 flag.setOnOff(buffer_->params().compressed);
701                 break;
702         }
703
704         default:
705                 flag.enabled(false);
706         }
707
708         return flag;
709 }
710
711
712 Update::flags BufferView::dispatch(FuncRequest const & cmd)
713 {
714         //lyxerr << BOOST_CURRENT_FUNCTION
715         //       << [ cmd = " << cmd << "]" << endl;
716
717         // Make sure that the cached BufferView is correct.
718         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
719                 << " action[" << cmd.action << ']'
720                 << " arg[" << to_utf8(cmd.argument()) << ']'
721                 << " x[" << cmd.x << ']'
722                 << " y[" << cmd.y << ']'
723                 << " button[" << cmd.button() << ']'
724                 << endl;
725
726         // FIXME: this should not be possible.
727         if (!buffer_)
728                 return Update::None;
729
730         LCursor & cur = cursor_;
731         // Default Update flags.
732         Update::flags updateFlags = Update::Force | Update::FitCursor;
733
734         switch (cmd.action) {
735
736         case LFUN_UNDO:
737                 cur.message(_("Undo"));
738                 cur.clearSelection();
739                 if (!textUndo(*this)) {
740                         cur.message(_("No further undo information"));
741                         updateFlags = Update::None;
742                 }
743                 switchKeyMap();
744                 break;
745
746         case LFUN_REDO:
747                 cur.message(_("Redo"));
748                 cur.clearSelection();
749                 if (!textRedo(*this)) {
750                         cur.message(_("No further redo information"));
751                         updateFlags = Update::None;
752                 }
753                 switchKeyMap();
754                 break;
755
756         case LFUN_FILE_INSERT:
757                 // FIXME UNICODE
758                 menuInsertLyXFile(to_utf8(cmd.argument()));
759                 break;
760
761         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
762                 // FIXME UNICODE
763                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
764                 break;
765
766         case LFUN_FILE_INSERT_PLAINTEXT:
767                 // FIXME UNICODE
768                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
769                 break;
770
771         case LFUN_FONT_STATE:
772                 cur.message(cur.currentState());
773                 break;
774
775         case LFUN_BOOKMARK_SAVE:
776                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
777                 break;
778
779         case LFUN_LABEL_GOTO: {
780                 docstring label = cmd.argument();
781                 if (label.empty()) {
782                         InsetRef * inset =
783                                 getInsetByCode<InsetRef>(cursor_,
784                                                          InsetBase::REF_CODE);
785                         if (inset) {
786                                 label = inset->getParam("reference");
787                                 // persistent=false: use temp_bookmark
788                                 saveBookmark(false);
789                         }
790                 }
791
792                 if (!label.empty())
793                         gotoLabel(label);
794                 break;
795         }
796
797         case LFUN_PARAGRAPH_GOTO: {
798                 int const id = convert<int>(to_utf8(cmd.argument()));
799                 int i = 0;
800                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
801                         ParIterator par = b->getParFromID(id);
802                         if (par == b->par_iterator_end()) {
803                                 lyxerr[Debug::INFO]
804                                         << "No matching paragraph found! ["
805                                         << id << "]." << endl;
806                         } else {
807                                 lyxerr[Debug::INFO]
808                                         << "Paragraph " << par->id()
809                                         << " found in buffer `"
810                                         << b->fileName() << "'." << endl;
811
812                                 if (b == buffer_) {
813                                         // Set the cursor
814                                         setCursor(makeDocIterator(par, 0));
815                                         switchKeyMap();
816                                 } else {
817                                         // Switch to other buffer view and resend cmd
818                                         theLyXFunc().dispatch(FuncRequest(
819                                                 LFUN_BUFFER_SWITCH, b->fileName()));
820                                         theLyXFunc().dispatch(cmd);
821                                         updateFlags = Update::None;
822                                 }
823                                 break;
824                         }
825                         ++i;
826                 }
827                 break;
828         }
829
830         case LFUN_OUTLINE_UP:
831                 toc::outline(toc::Up, cursor_);
832                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
833                 updateLabels(*buffer_);
834                 break;
835         case LFUN_OUTLINE_DOWN:
836                 toc::outline(toc::Down, cursor_);
837                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
838                 updateLabels(*buffer_);
839                 break;
840         case LFUN_OUTLINE_IN:
841                 toc::outline(toc::In, cursor_);
842                 updateLabels(*buffer_);
843                 break;
844         case LFUN_OUTLINE_OUT:
845                 toc::outline(toc::Out, cursor_);
846                 updateLabels(*buffer_);
847                 break;
848
849         case LFUN_NOTE_NEXT:
850                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
851                 break;
852
853         case LFUN_REFERENCE_NEXT: {
854                 vector<InsetBase_code> tmp;
855                 tmp.push_back(InsetBase::LABEL_CODE);
856                 tmp.push_back(InsetBase::REF_CODE);
857                 bv_funcs::gotoInset(this, tmp, true);
858                 break;
859         }
860
861         case LFUN_CHANGES_TRACK:
862                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
863                 break;
864
865         case LFUN_CHANGES_OUTPUT:
866                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
867                 break;
868
869         case LFUN_CHANGE_NEXT:
870                 findNextChange(this);
871                 break;
872
873         case LFUN_CHANGES_MERGE:
874                 if (findNextChange(this))
875                         showDialog("changes");
876                 break;
877
878         case LFUN_ALL_CHANGES_ACCEPT: {
879                 cursor_.reset(buffer_->inset());
880 #ifdef WITH_WARNINGS
881 #warning FIXME changes
882 #endif
883                 while (findNextChange(this))
884                         getLyXText()->acceptOrRejectChanges(cursor_, LyXText::ACCEPT);
885                 break;
886         }
887
888         case LFUN_ALL_CHANGES_REJECT: {
889                 cursor_.reset(buffer_->inset());
890 #ifdef WITH_WARNINGS
891 #warning FIXME changes
892 #endif
893                 while (findNextChange(this))
894                         getLyXText()->acceptOrRejectChanges(cursor_, LyXText::REJECT);
895                 break;
896         }
897
898         case LFUN_WORD_FIND:
899                 find(this, cmd);
900                 break;
901
902         case LFUN_WORD_REPLACE:
903                 replace(this, cmd);
904                 break;
905
906         case LFUN_MARK_OFF:
907                 cur.clearSelection();
908                 cur.resetAnchor();
909                 cur.message(from_utf8(N_("Mark off")));
910                 break;
911
912         case LFUN_MARK_ON:
913                 cur.clearSelection();
914                 cur.mark() = true;
915                 cur.resetAnchor();
916                 cur.message(from_utf8(N_("Mark on")));
917                 break;
918
919         case LFUN_MARK_TOGGLE:
920                 cur.clearSelection();
921                 if (cur.mark()) {
922                         cur.mark() = false;
923                         cur.message(from_utf8(N_("Mark removed")));
924                 } else {
925                         cur.mark() = true;
926                         cur.message(from_utf8(N_("Mark set")));
927                 }
928                 cur.resetAnchor();
929                 break;
930
931         case LFUN_SCREEN_RECENTER:
932                 center();
933                 break;
934
935         case LFUN_BIBTEX_DATABASE_ADD: {
936                 LCursor tmpcur = cursor_;
937                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
938                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
939                                                 InsetBase::BIBTEX_CODE);
940                 if (inset) {
941                         if (inset->addDatabase(to_utf8(cmd.argument())))
942                                 buffer_->updateBibfilesCache();
943                 }
944                 break;
945         }
946
947         case LFUN_BIBTEX_DATABASE_DEL: {
948                 LCursor tmpcur = cursor_;
949                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
950                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
951                                                 InsetBase::BIBTEX_CODE);
952                 if (inset) {
953                         if (inset->delDatabase(to_utf8(cmd.argument())))
954                                 buffer_->updateBibfilesCache();
955                 }
956                 break;
957         }
958
959         case LFUN_WORDS_COUNT: {
960                 DocIterator from, to;
961                 if (cur.selection()) {
962                         from = cur.selectionBegin();
963                         to = cur.selectionEnd();
964                 } else {
965                         from = doc_iterator_begin(buffer_->inset());
966                         to = doc_iterator_end(buffer_->inset());
967                 }
968                 int const count = countWords(from, to);
969                 docstring message;
970                 if (count != 1) {
971                         if (cur.selection())
972                                 message = bformat(_("%1$d words in selection."),
973                                           count);
974                                 else
975                                         message = bformat(_("%1$d words in document."),
976                                                           count);
977                 }
978                 else {
979                         if (cur.selection())
980                                 message = _("One word in selection.");
981                         else
982                                 message = _("One word in document.");
983                 }
984
985                 Alert::information(_("Count words"), message);
986         }
987                 break;
988
989         case LFUN_BUFFER_TOGGLE_COMPRESSION:
990                 // turn compression on/off
991                 buffer_->params().compressed = !buffer_->params().compressed;
992                 break;
993
994         case LFUN_NEXT_INSET_TOGGLE: {
995                 // this is the real function we want to invoke
996                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
997                 // if there is an inset at cursor, see whether it
998                 // wants to toggle.
999                 InsetBase * inset = cur.nextInset();
1000                 if (inset && inset->isActive()) {
1001                         LCursor tmpcur = cur;
1002                         tmpcur.pushLeft(*inset);
1003                         inset->dispatch(tmpcur, tmpcmd);
1004                         if (tmpcur.result().dispatched()) {
1005                                 cur.dispatched();
1006                         }
1007                 }
1008                 // if it did not work, try the underlying inset.
1009                 if (!cur.result().dispatched())
1010                         cur.dispatch(tmpcmd);
1011
1012                 if (cur.result().dispatched())
1013                         cur.clearSelection();
1014
1015                 break;
1016         }
1017
1018         default:
1019                 updateFlags = Update::None;
1020         }
1021
1022         return updateFlags;
1023 }
1024
1025
1026 docstring const BufferView::requestSelection()
1027 {
1028         if (!buffer_)
1029                 return docstring();
1030
1031         LCursor & cur = cursor_;
1032
1033         if (!cur.selection()) {
1034                 xsel_cache_.set = false;
1035                 return docstring();
1036         }
1037
1038         if (!xsel_cache_.set ||
1039             cur.top() != xsel_cache_.cursor ||
1040             cur.anchor_.top() != xsel_cache_.anchor)
1041         {
1042                 xsel_cache_.cursor = cur.top();
1043                 xsel_cache_.anchor = cur.anchor_.top();
1044                 xsel_cache_.set = cur.selection();
1045                 return cur.selectionAsString(false);
1046         }
1047         return docstring();
1048 }
1049
1050
1051 void BufferView::clearSelection()
1052 {
1053         if (buffer_) {
1054                 cursor_.clearSelection();
1055                 xsel_cache_.set = false;
1056                 // The buffer did not really change, but this causes the
1057                 // redraw we need because we cleared the selection above.
1058                 buffer_->changed();
1059         }
1060 }
1061
1062
1063 void BufferView::workAreaResize(int width, int height)
1064 {
1065         // Update from work area
1066         width_ = width;
1067         height_ = height;
1068
1069         // The complete text metrics will be redone.
1070         text_metrics_.clear();
1071
1072         if (buffer_)
1073                 resize();
1074 }
1075
1076
1077 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1078 {
1079         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1080
1081         // This is only called for mouse related events including
1082         // LFUN_FILE_OPEN generated by drag-and-drop.
1083         FuncRequest cmd = cmd0;
1084
1085         // E.g. Qt mouse press when no buffer
1086         if (!buffer_)
1087                 return false;
1088
1089         LCursor cur(*this);
1090         cur.push(buffer_->inset());
1091         cur.selection() = cursor_.selection();
1092
1093         // Either the inset under the cursor or the
1094         // surrounding LyXText will handle this event.
1095
1096         // Build temporary cursor.
1097         cmd.y = min(max(cmd.y, -1), height_);
1098         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1099
1100         //lyxerr << BOOST_CURRENT_FUNCTION
1101         //       << " * hit inset at tip: " << inset << endl;
1102         //lyxerr << BOOST_CURRENT_FUNCTION
1103         //       << " * created temp cursor:" << cur << endl;
1104
1105         // NOTE: editXY returns the top level inset of nested insets. If you happen
1106         // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1107         // footnote inset, again inset=0), that inset will not be redrawn.
1108         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1109                 bool need_redraw = false;
1110                 
1111                 if (inset != last_inset_) {
1112                         if (last_inset_)
1113                                 need_redraw |= last_inset_->setMouseHover(false);
1114                         if (inset)
1115                                 need_redraw |= inset->setMouseHover(true);
1116                         last_inset_ = inset;
1117                 }
1118
1119                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1120                 // not expose the button for redraw. We adjust here the metrics dimension
1121                 // to enable a full redraw.
1122                 // FIXME: It is possible to redraw only the area around the button!
1123                 if (need_redraw 
1124                         && metrics_info_.update_strategy == SingleParUpdate) {
1125                         // FIXME: It should be possible to redraw only the area around 
1126                         // the button by doing this:
1127                         //
1128                         //metrics_info_.singlepar = false;
1129                         //metrics_info_.y1 = ymin of button;
1130                         //metrics_info_.y2 = ymax of button;
1131                         //
1132                         // Unfortunately, rowpainter.C:paintText() does not distinguish
1133                         // between background updates and text updates. So we use the hammer
1134                         // solution for now. We could also avoid the updateMetrics() below
1135                         // by using the first and last pit of the CoordCache. Have a look
1136                         // at LyXText::getPitNearY() to see what I mean.
1137                         //
1138                         //metrics_info_.pit1 = first pit of CoordCache;
1139                         //metrics_info_.pit2 = last pit of CoordCache;
1140                         //metrics_info_.singlepar = false;
1141                         //metrics_info_.y1 = 0;
1142                         //metrics_info_.y2 = height_;
1143                         //
1144                         updateMetrics(false);
1145                 }
1146
1147                 // This event (moving without mouse click) is not passed further.
1148                 // This should be changed if it is further utilized.
1149                 return need_redraw;
1150         }
1151
1152         // Put anchor at the same position.
1153         cur.resetAnchor();
1154
1155         // Try to dispatch to an non-editable inset near this position
1156         // via the temp cursor. If the inset wishes to change the real
1157         // cursor it has to do so explicitly by using
1158         //  cur.bv().cursor() = cur;  (or similar)
1159         if (inset) {
1160                 inset->dispatch(cur, cmd);
1161         }
1162
1163         // Now dispatch to the temporary cursor. If the real cursor should
1164         // be modified, the inset's dispatch has to do so explicitly.
1165         if (!cur.result().dispatched())
1166                 cur.dispatch(cmd);
1167
1168         // Redraw if requested and necessary.
1169         if (cur.result().dispatched() && cur.result().update())
1170                 return update(cur.result().update());
1171
1172         return false;
1173 }
1174
1175
1176 void BufferView::scroll(int /*lines*/)
1177 {
1178 //      if (!buffer_)
1179 //              return;
1180 //
1181 //      LyXText const * t = &buffer_->text();
1182 //      int const line_height = defaultRowHeight();
1183 //
1184 //      // The new absolute coordinate
1185 //      int new_top_y = top_y() + lines * line_height;
1186 //
1187 //      // Restrict to a valid value
1188 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1189 //      new_top_y = std::max(0, new_top_y);
1190 //
1191 //      scrollDocView(new_top_y);
1192 //
1193 }
1194
1195
1196 void BufferView::setCursorFromRow(int row)
1197 {
1198         int tmpid = -1;
1199         int tmppos = -1;
1200
1201         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1202
1203         if (tmpid == -1)
1204                 buffer_->text().setCursor(cursor_, 0, 0);
1205         else
1206                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1207 }
1208
1209
1210 void BufferView::gotoLabel(docstring const & label)
1211 {
1212         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1213                 vector<docstring> labels;
1214                 it->getLabelList(*buffer_, labels);
1215                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1216                         setCursor(it);
1217                         update();
1218                         return;
1219                 }
1220         }
1221 }
1222
1223
1224 LyXText * BufferView::getLyXText()
1225 {
1226         LyXText * text = cursor_.innerText();
1227         BOOST_ASSERT(text);
1228         return text;
1229 }
1230
1231
1232 LyXText const * BufferView::getLyXText() const
1233 {
1234         LyXText const * text = cursor_.innerText();
1235         BOOST_ASSERT(text);
1236         return text;
1237 }
1238
1239
1240 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1241 {
1242         return const_cast<BufferView *>(this)->textMetrics(t);
1243 }
1244
1245
1246 TextMetrics & BufferView::textMetrics(LyXText const * t)
1247 {
1248         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1249         if (tmc_it == text_metrics_.end()) {
1250                 tmc_it = text_metrics_.insert(
1251                         make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1252         }       
1253         return tmc_it->second;
1254 }
1255
1256
1257 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1258                 pit_type pit) const
1259 {
1260         return textMetrics(t).parMetrics(pit);
1261 }
1262
1263
1264 int BufferView::workHeight() const
1265 {
1266         return height_;
1267 }
1268
1269
1270 void BufferView::setCursor(DocIterator const & dit)
1271 {
1272         size_t const n = dit.depth();
1273         for (size_t i = 0; i < n; ++i)
1274                 dit[i].inset().edit(cursor_, true);
1275
1276         cursor_.setCursor(dit);
1277         cursor_.selection() = false;
1278 }
1279
1280
1281 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1282 {
1283         // Would be wrong to delete anything if we have a selection.
1284         if (cur.selection())
1285                 return false;
1286
1287         bool need_anchor_change = false;
1288         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1289                 need_anchor_change);
1290
1291         if (need_anchor_change)
1292                 cur.resetAnchor();
1293         
1294         if (!changed)
1295                 return false;
1296
1297         updateMetrics(false);
1298         buffer_->changed();
1299         return true;
1300 }
1301
1302
1303 bool BufferView::mouseSetCursor(LCursor & cur)
1304 {
1305         BOOST_ASSERT(&cur.bv() == this);
1306
1307         // Has the cursor just left the inset?
1308         bool badcursor = false;
1309         if (&cursor_.inset() != &cur.inset())
1310                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1311
1312         // do the dEPM magic if needed
1313         // FIXME: move this to InsetText::notifyCursorLeaves?
1314         bool update = false;
1315         if (!badcursor && cursor_.inTexted())
1316                 checkDepm(cur, cursor_);
1317
1318         // if the cursor was in an empty script inset and the new
1319         // position is in the nucleus of the inset, notifyCursorLeaves
1320         // will kill the script inset itself. So we check all the
1321         // elements of the cursor to make sure that they are correct.
1322         // For an example, see bug 2933: 
1323         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1324         // The code below could maybe be moved to a DocIterator method.
1325         //lyxerr << "cur before " << cur <<std::endl;
1326         DocIterator dit(cur.inset());
1327         dit.push_back(cur.bottom());
1328         size_t i = 1;
1329         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1330                 dit.push_back(cur[i]);
1331                 ++i;
1332         }
1333         //lyxerr << "5 cur after" << dit <<std::endl;
1334
1335         cursor_.setCursor(dit);
1336         cursor_.clearSelection();
1337         // remember new position.
1338         cursor_.setTargetX();
1339         finishUndo();
1340         return update;
1341 }
1342
1343
1344 void BufferView::putSelectionAt(DocIterator const & cur,
1345                                 int length, bool backwards)
1346 {
1347         cursor_.clearSelection();
1348
1349         setCursor(cur);
1350
1351         if (length) {
1352                 if (backwards) {
1353                         cursor_.pos() += length;
1354                         cursor_.setSelection(cursor_, -length);
1355                 } else
1356                         cursor_.setSelection(cursor_, length);
1357                 theSelection().haveSelection(cursor_.selection());
1358         }
1359 }
1360
1361
1362 LCursor & BufferView::cursor()
1363 {
1364         return cursor_;
1365 }
1366
1367
1368 LCursor const & BufferView::cursor() const
1369 {
1370         return cursor_;
1371 }
1372
1373
1374 pit_type BufferView::anchor_ref() const
1375 {
1376         return anchor_ref_;
1377 }
1378
1379
1380 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1381 {
1382         return metrics_info_;
1383 }
1384
1385
1386 // FIXME: We should split-up updateMetrics() for the singlepar case.
1387 void BufferView::updateMetrics(bool singlepar)
1388 {
1389         LyXText & buftext = buffer_->text();
1390         TextMetrics & tm = textMetrics(&buftext);
1391         pit_type size = int(buftext.paragraphs().size());
1392
1393         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1394                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1395                 offset_ref_ = 0;
1396         }
1397         
1398         // If the paragraph metrics has changed, we can not
1399         // use the singlepar optimisation.
1400         if (singlepar
1401                 // In Single Paragraph mode, rebreak only
1402                 // the (main text, not inset!) paragraph containing the cursor.
1403                 // (if this paragraph contains insets etc., rebreaking will
1404                 // recursively descend)
1405                 && tm.redoParagraph(cursor_.bottom().pit()))
1406                 singlepar = false;
1407
1408         pit_type const pit = anchor_ref_;
1409         int pit1 = pit;
1410         int pit2 = pit;
1411         size_t const npit = buftext.paragraphs().size();
1412
1413         // Rebreak anchor paragraph.
1414         if (!singlepar)
1415                 tm.redoParagraph(pit);
1416         
1417         // Clear out the position cache in case of full screen redraw.
1418         if (!singlepar)
1419                 coord_cache_.clear();
1420
1421         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1422
1423         // Redo paragraphs above anchor if necessary.
1424         int y1 = y0;
1425         while (y1 > 0 && pit1 > 0) {
1426                 y1 -= tm.parMetrics(pit1).ascent();
1427                 --pit1;
1428                 if (!singlepar)
1429                         tm.redoParagraph(pit1);
1430                 y1 -= tm.parMetrics(pit1).descent();
1431         }
1432
1433
1434         // Take care of ascent of first line
1435         y1 -= tm.parMetrics(pit1).ascent();
1436
1437         // Normalize anchor for next time
1438         anchor_ref_ = pit1;
1439         offset_ref_ = -y1;
1440
1441         // Grey at the beginning is ugly
1442         if (pit1 == 0 && y1 > 0) {
1443                 y0 -= y1;
1444                 y1 = 0;
1445                 anchor_ref_ = 0;
1446         }
1447
1448         // Redo paragraphs below the anchor if necessary.
1449         int y2 = y0;
1450         while (y2 < height_ && pit2 < int(npit) - 1) {
1451                 y2 += tm.parMetrics(pit2).descent();
1452                 ++pit2;
1453                 if (!singlepar)
1454                         tm.redoParagraph(pit2);
1455                 y2 += tm.parMetrics(pit2).ascent();
1456         }
1457
1458         // Take care of descent of last line
1459         y2 += tm.parMetrics(pit2).descent();
1460
1461         // The coordinates of all these paragraphs are correct, cache them
1462         int y = y1;
1463         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1464         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1465                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1466                 y += pm.ascent();
1467                 parPos[pit] = Point(0, y);
1468                 if (singlepar && pit == cursor_.bottom().pit()) {
1469                         // In Single Paragraph mode, collect here the
1470                         // y1 and y2 of the (one) paragraph the cursor is in
1471                         y1 = y - pm.ascent();
1472                         y2 = y + pm.descent();
1473                 }
1474                 y += pm.descent();
1475         }
1476
1477         if (singlepar) {
1478                 // collect cursor paragraph iter bounds
1479                 pit1 = cursor_.bottom().pit();
1480                 pit2 = cursor_.bottom().pit();
1481         }
1482
1483         lyxerr[Debug::DEBUG]
1484                 << BOOST_CURRENT_FUNCTION
1485                 << " y1: " << y1
1486                 << " y2: " << y2
1487                 << " pit1: " << pit1
1488                 << " pit2: " << pit2
1489                 << " npit: " << npit
1490                 << " singlepar: " << singlepar
1491                 << "size: " << size
1492                 << endl;
1493
1494         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, 
1495                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1496
1497         if (lyxerr.debugging(Debug::WORKAREA)) {
1498                 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1499                 coord_cache_.dump();
1500         }
1501 }
1502
1503
1504 void BufferView::menuInsertLyXFile(string const & filenm)
1505 {
1506         BOOST_ASSERT(cursor_.inTexted());
1507         string filename = filenm;
1508
1509         if (filename.empty()) {
1510                 // Launch a file browser
1511                 // FIXME UNICODE
1512                 string initpath = lyxrc.document_path;
1513
1514                 if (buffer_) {
1515                         string const trypath = buffer_->filePath();
1516                         // If directory is writeable, use this as default.
1517                         if (isDirWriteable(FileName(trypath)))
1518                                 initpath = trypath;
1519                 }
1520
1521                 // FIXME UNICODE
1522                 FileDialog fileDlg(_("Select LyX document to insert"),
1523                         LFUN_FILE_INSERT,
1524                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1525                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1526
1527                 FileDialog::Result result =
1528                         fileDlg.open(from_utf8(initpath),
1529                                      FileFilterList(_("LyX Documents (*.lyx)")),
1530                                      docstring());
1531
1532                 if (result.first == FileDialog::Later)
1533                         return;
1534
1535                 // FIXME UNICODE
1536                 filename = to_utf8(result.second);
1537
1538                 // check selected filename
1539                 if (filename.empty()) {
1540                         // emit message signal.
1541                         message(_("Canceled."));
1542                         return;
1543                 }
1544         }
1545
1546         // Get absolute path of file and add ".lyx"
1547         // to the filename if necessary
1548         filename = fileSearch(string(), filename, "lyx").absFilename();
1549
1550         docstring const disp_fn = makeDisplayPath(filename);
1551         // emit message signal.
1552         message(bformat(_("Inserting document %1$s..."), disp_fn));
1553
1554         docstring res;
1555         Buffer buf("", false);
1556         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1557                 ErrorList & el = buffer_->errorList("Parse");
1558                 // Copy the inserted document error list into the current buffer one.
1559                 el = buf.errorList("Parse");
1560                 recordUndo(cursor_);
1561                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1562                                              buf.params().textclass, el);
1563                 res = _("Document %1$s inserted.");
1564         } else
1565                 res = _("Could not insert document %1$s");
1566
1567         // emit message signal.
1568         message(bformat(res, disp_fn));
1569         buffer_->errors("Parse");
1570         resize();
1571 }
1572
1573 } // namespace lyx