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