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