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