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