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