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