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