]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
709da3c6f6caf07c73a642736753e63b8fe1a505
[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 void BufferView::selectionRequested()
1018 {
1019         static docstring sel;
1020
1021         if (!buffer_)
1022                 return;
1023
1024         LCursor & cur = cursor_;
1025
1026         if (!cur.selection()) {
1027                 xsel_cache_.set = false;
1028                 return;
1029         }
1030
1031         if (!xsel_cache_.set ||
1032             cur.top() != xsel_cache_.cursor ||
1033             cur.anchor_.top() != xsel_cache_.anchor)
1034         {
1035                 xsel_cache_.cursor = cur.top();
1036                 xsel_cache_.anchor = cur.anchor_.top();
1037                 xsel_cache_.set = cur.selection();
1038                 sel = cur.selectionAsString(false);
1039                 if (!sel.empty())
1040                         owner_->gui().selection().put(sel);
1041         }
1042 }
1043
1044
1045 void BufferView::selectionLost()
1046 {
1047         if (buffer_) {
1048                 cursor_.clearSelection();
1049                 xsel_cache_.set = false;
1050         }
1051 }
1052
1053
1054 void BufferView::workAreaResize(int width, int height)
1055 {
1056         bool const widthChange = width != width_;
1057         bool const heightChange = height != height_;
1058
1059         // Update from work area
1060         width_ = width;
1061         height_ = height;
1062
1063         if (buffer_ && widthChange) {
1064                 // The WorkArea content needs a resize
1065                 resize();
1066         }
1067
1068         if (widthChange || heightChange)
1069                 update();
1070 }
1071
1072
1073 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1074 {
1075         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1076
1077         // This is only called for mouse related events including
1078         // LFUN_FILE_OPEN generated by drag-and-drop.
1079         FuncRequest cmd = cmd0;
1080
1081         if (!buffer_)
1082                 return false;
1083
1084         LCursor cur(*this);
1085         cur.push(buffer_->inset());
1086         cur.selection() = cursor_.selection();
1087
1088         // Doesn't go through lyxfunc, so we need to update
1089         // the layout choice etc. ourselves
1090
1091         // E.g. Qt mouse press when no buffer
1092         if (!buffer_)
1093                 return false;
1094
1095         // Either the inset under the cursor or the
1096         // surrounding LyXText will handle this event.
1097
1098         // Build temporary cursor.
1099         cmd.y = min(max(cmd.y, -1), height_);
1100         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1101         //lyxerr << BOOST_CURRENT_FUNCTION
1102         //       << " * hit inset at tip: " << inset << endl;
1103         //lyxerr << BOOST_CURRENT_FUNCTION
1104         //       << " * created temp cursor:" << cur << endl;
1105
1106         // Put anchor at the same position.
1107         cur.resetAnchor();
1108
1109         // Try to dispatch to an non-editable inset near this position
1110         // via the temp cursor. If the inset wishes to change the real
1111         // cursor it has to do so explicitly by using
1112         //  cur.bv().cursor() = cur;  (or similar)
1113         if (inset)
1114                 inset->dispatch(cur, cmd);
1115
1116         // Now dispatch to the temporary cursor. If the real cursor should
1117         // be modified, the inset's dispatch has to do so explicitly.
1118         if (!cur.result().dispatched())
1119                 cur.dispatch(cmd);
1120
1121         if (cur.result().dispatched()) {
1122                 // Redraw if requested or necessary.
1123                 if (cur.result().update())
1124                         update(Update::FitCursor | Update::Force);
1125                 else
1126                         update(Update::FitCursor | Update::MultiParSel);
1127         }
1128
1129         return true;
1130 }
1131
1132
1133 void BufferView::scroll(int lines)
1134 {
1135 //      if (!buffer_)
1136 //              return;
1137 //
1138 //      LyXText const * t = &buffer_->text();
1139 //      int const line_height = defaultRowHeight();
1140 //
1141 //      // The new absolute coordinate
1142 //      int new_top_y = top_y() + lines * line_height;
1143 //
1144 //      // Restrict to a valid value
1145 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1146 //      new_top_y = std::max(0, new_top_y);
1147 //
1148 //      scrollDocView(new_top_y);
1149 //
1150 //      // Update the scrollbar.
1151 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1152 }
1153
1154
1155 void BufferView::setCursorFromRow(int row)
1156 {
1157         int tmpid = -1;
1158         int tmppos = -1;
1159
1160         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1161
1162         if (tmpid == -1)
1163                 buffer_->text().setCursor(cursor_, 0, 0);
1164         else
1165                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1166 }
1167
1168
1169 void BufferView::gotoLabel(string const & label)
1170 {
1171         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1172                 vector<string> labels;
1173                 it->getLabelList(*buffer_, labels);
1174                 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1175                         setCursor(it);
1176                         update();
1177                         return;
1178                 }
1179         }
1180 }
1181
1182
1183 LyXText * BufferView::getLyXText()
1184 {
1185         LyXText * text = cursor_.innerText();
1186         BOOST_ASSERT(text);
1187         return text;
1188 }
1189
1190
1191 LyXText const * BufferView::getLyXText() const
1192 {
1193         LyXText const * text = cursor_.innerText();
1194         BOOST_ASSERT(text);
1195         return text;
1196 }
1197
1198
1199 int BufferView::workHeight() const
1200 {
1201         return height_;
1202 }
1203
1204
1205 void BufferView::setCursor(DocIterator const & dit)
1206 {
1207         size_t const n = dit.depth();
1208         for (size_t i = 0; i < n; ++i)
1209                 dit[i].inset().edit(cursor_, true);
1210
1211         cursor_.setCursor(dit);
1212         cursor_.selection() = false;
1213 }
1214
1215
1216 void BufferView::mouseSetCursor(LCursor & cur)
1217 {
1218         BOOST_ASSERT(&cur.bv() == this);
1219
1220         // Has the cursor just left the inset?
1221         bool badcursor = false;
1222         if (&cursor_.inset() != &cur.inset())
1223                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1224
1225         // do the dEPM magic if needed
1226         // FIXME: move this to InsetText::notifyCursorLeaves?
1227         if (!badcursor && cursor_.inTexted())
1228                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1229
1230         cursor_ = cur;
1231         cursor_.clearSelection();
1232         cursor_.setTargetX();
1233         finishUndo();
1234
1235 }
1236
1237
1238 void BufferView::putSelectionAt(DocIterator const & cur,
1239                                 int length, bool backwards)
1240 {
1241         cursor_.clearSelection();
1242
1243         setCursor(cur);
1244
1245         if (length) {
1246                 if (backwards) {
1247                         cursor_.pos() += length;
1248                         cursor_.setSelection(cursor_, -length);
1249                 } else
1250                         cursor_.setSelection(cursor_, length);
1251         }
1252 }
1253
1254
1255 LCursor & BufferView::cursor()
1256 {
1257         return cursor_;
1258 }
1259
1260
1261 LCursor const & BufferView::cursor() const
1262 {
1263         return cursor_;
1264 }
1265
1266
1267 lyx::pit_type BufferView::anchor_ref() const
1268 {
1269         return anchor_ref_;
1270 }
1271
1272
1273 int BufferView::offset_ref() const
1274 {
1275         return offset_ref_;
1276 }
1277
1278
1279 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1280 {
1281         return metrics_info_;
1282 }
1283
1284
1285 void BufferView::updateMetrics(bool singlepar)
1286 {
1287         // Remove old position cache
1288         theCoords.clear();
1289         LyXText & buftext = buffer_->text();
1290         lyx::pit_type size = int(buftext.paragraphs().size());
1291
1292         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1293                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1294                 offset_ref_ = 0;
1295         }
1296
1297         lyx::pit_type const pit = anchor_ref_;
1298         int pit1 = pit;
1299         int pit2 = pit;
1300         size_t const npit = buftext.paragraphs().size();
1301
1302         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1303         // the (main text, not inset!) paragraph containing the cursor.
1304         // (if this paragraph contains insets etc., rebreaking will
1305         // recursively descend)
1306         if (!singlepar || pit == cursor_.bottom().pit())
1307                 buftext.redoParagraph(pit);
1308         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1309
1310         // Redo paragraphs above anchor if necessary; again, in Single Par
1311         // mode, only if we encounter the (main text) one having the cursor.
1312         int y1 = y0;
1313         while (y1 > 0 && pit1 > 0) {
1314                 y1 -= buftext.getPar(pit1).ascent();
1315                 --pit1;
1316                 if (!singlepar || pit1 == cursor_.bottom().pit())
1317                         buftext.redoParagraph(pit1);
1318                 y1 -= buftext.getPar(pit1).descent();
1319         }
1320
1321
1322         // Take care of ascent of first line
1323         y1 -= buftext.getPar(pit1).ascent();
1324
1325         // Normalize anchor for next time
1326         anchor_ref_ = pit1;
1327         offset_ref_ = -y1;
1328
1329         // Grey at the beginning is ugly
1330         if (pit1 == 0 && y1 > 0) {
1331                 y0 -= y1;
1332                 y1 = 0;
1333                 anchor_ref_ = 0;
1334         }
1335
1336         // Redo paragraphs below the anchor if necessary. Single par mode:
1337         // only the one containing the cursor if encountered.
1338         int y2 = y0;
1339         while (y2 < height_ && pit2 < int(npit) - 1) {
1340                 y2 += buftext.getPar(pit2).descent();
1341                 ++pit2;
1342                 if (!singlepar || pit2 == cursor_.bottom().pit())
1343                         buftext.redoParagraph(pit2);
1344                 y2 += buftext.getPar(pit2).ascent();
1345         }
1346
1347         // Take care of descent of last line
1348         y2 += buftext.getPar(pit2).descent();
1349
1350         // The coordinates of all these paragraphs are correct, cache them
1351         int y = y1;
1352         CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1353         for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1354                 Paragraph const & par = buftext.getPar(pit);
1355                 y += par.ascent();
1356                 parPos[pit] = Point(0, y);
1357                 if (singlepar && pit == cursor_.bottom().pit()) {
1358                         // In Single Paragraph mode, collect here the
1359                         // y1 and y2 of the (one) paragraph the cursor is in
1360                         y1 = y - par.ascent();
1361                         y2 = y + par.descent();
1362                 }
1363                 y += par.descent();
1364         }
1365
1366         if (singlepar) {
1367                 // collect cursor paragraph iter bounds
1368                 pit1 = cursor_.bottom().pit();
1369                 pit2 = cursor_.bottom().pit();
1370         }
1371
1372         lyxerr[Debug::DEBUG]
1373                 << BOOST_CURRENT_FUNCTION
1374                 << " y1: " << y1
1375                 << " y2: " << y2
1376                 << " pit1: " << pit1
1377                 << " pit2: " << pit2
1378                 << " npit: " << npit
1379                 << " singlepar: " << singlepar
1380                 << "size: " << size
1381                 << endl;
1382
1383         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1384 }
1385
1386
1387 void BufferView::menuInsertLyXFile(string const & filenm)
1388 {
1389         BOOST_ASSERT(cursor_.inTexted());
1390         string filename = filenm;
1391
1392         if (filename.empty()) {
1393                 // Launch a file browser
1394                 string initpath = lyxrc.document_path;
1395
1396                 if (buffer_) {
1397                         string const trypath = buffer_->filePath();
1398                         // If directory is writeable, use this as default.
1399                         if (isDirWriteable(trypath))
1400                                 initpath = trypath;
1401                 }
1402
1403                 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1404                         LFUN_FILE_INSERT,
1405                         make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1406                                   string(lyxrc.document_path)),
1407                         make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1408                                   string(addPath(package().system_support(), "examples"))));
1409
1410                 FileDialog::Result result =
1411                         fileDlg.open(initpath,
1412                                      FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1413                                      string());
1414
1415                 if (result.first == FileDialog::Later)
1416                         return;
1417
1418                 filename = result.second;
1419
1420                 // check selected filename
1421                 if (filename.empty()) {
1422                         // emit message signal.
1423                         message(_("Canceled."));
1424                         return;
1425                 }
1426         }
1427
1428         // Get absolute path of file and add ".lyx"
1429         // to the filename if necessary
1430         filename = fileSearch(string(), filename, "lyx");
1431
1432         docstring const disp_fn = makeDisplayPath(filename);
1433         // emit message signal.
1434         message(bformat(_("Inserting document %1$s..."), disp_fn));
1435
1436         docstring res;
1437         Buffer buf("", false);
1438         if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1439                 ErrorList & el = buffer_->errorList("Parse");
1440                 // Copy the inserted document error list into the current buffer one.
1441                 el = buf.errorList("Parse");
1442                 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1443                                              buf.params().textclass, el);
1444                 res = _("Document %1$s inserted.");
1445         } else
1446                 res = _("Could not insert document %1$s");
1447
1448         // emit message signal.
1449         message(bformat(res, disp_fn));
1450         buffer_->errors("Parse");
1451         resize();
1452 }
1453
1454
1455 void BufferView::trackChanges()
1456 {
1457         bool const tracking = buffer_->params().tracking_changes;
1458
1459         if (!tracking) {
1460                 for_each(buffer_->par_iterator_begin(),
1461                          buffer_->par_iterator_end(),
1462                          bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1463                 buffer_->params().tracking_changes = true;
1464
1465                 // We cannot allow undos beyond the freeze point
1466                 buffer_->undostack().clear();
1467         } else {
1468                 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1469                 if (lyx::find::findNextChange(this)) {
1470                         owner_->getDialogs().show("changes");
1471                         return;
1472                 }
1473
1474                 for_each(buffer_->par_iterator_begin(),
1475                          buffer_->par_iterator_end(),
1476                          mem_fun_ref(&Paragraph::untrackChanges));
1477
1478                 buffer_->params().tracking_changes = false;
1479         }
1480
1481         buffer_->redostack().clear();
1482 }