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