]> git.lyx.org Git - lyx.git/blob - src/BufferView2.C
small cleanup
[lyx.git] / src / BufferView2.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *        
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <fstream>
12 #include <algorithm>
13
14 #include <config.h>
15
16 #include "BufferView.h"
17 #include "buffer.h"
18 #include "lyxcursor.h"
19 #include "lyxtext.h"
20 #include "insets/inseterror.h"
21 #include "LyXView.h"
22 #include "bufferlist.h"
23 #include "support/FileInfo.h"
24 #include "lyxscreen.h"
25 #include "support/filetools.h"
26 #include "frontends/Alert.h"
27 #include "LaTeX.h"
28 #include "BufferView_pimpl.h"
29 #include "insets/insetcommand.h" //ChangeRefs
30 #include "support/lyxfunctional.h" //equal_1st_in_pair
31 #include "language.h"
32 #include "gettext.h"
33 #include "undo_funcs.h"
34 #include "debug.h"
35 #include "iterators.h"
36
37 extern BufferList bufferlist;
38
39 using std::pair;
40 using std::endl;
41 using std::ifstream;
42 using std::vector;
43 using std::find;
44 using std::count;
45 using std::count_if;
46
47
48 // Inserts a file into current document
49 bool BufferView::insertLyXFile(string const & filen)
50         //
51         // Copyright CHT Software Service GmbH
52         // Uwe C. Schroeder
53         //
54         // Insert a Lyxformat - file into current buffer
55         //
56         // Moved from lyx_cb.C (Lgb)
57 {
58         if (filen.empty()) return false;
59
60         string const fname = MakeAbsPath(filen);
61
62         // check if file exist
63         FileInfo const fi(fname);
64
65         if (!fi.readable()) {
66                 Alert::alert(_("Error!"),
67                            _("Specified file is unreadable: "),
68                            MakeDisplayPath(fname, 50));
69                 return false;
70         }
71         
72         beforeChange(text);
73
74         ifstream ifs(fname.c_str());
75         if (!ifs) {
76                 Alert::alert(_("Error!"),
77                            _("Cannot open specified file: "),
78                            MakeDisplayPath(fname, 50));
79                 return false;
80         }
81         
82         int const c = ifs.peek();
83        
84         LyXLex lex(0, 0);
85         lex.setStream(ifs);
86
87         bool res = true;
88
89         if (c == '#') {
90                 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
91                 res = buffer()->readFile(lex, text->cursor.par());
92         } else {
93                 lyxerr[Debug::INFO] << "Will insert file without header" 
94                                     << endl;
95                 res = buffer()->readLyXformat2(lex, text->cursor.par());
96         }
97
98         resize();
99         return res;
100 }
101
102
103 bool BufferView::removeAutoInsets()
104 {
105         LyXCursor tmpcursor = text->cursor;
106         LyXCursor cursor;
107         bool found = false;
108
109         ParIterator end = buffer()->par_iterator_end();
110         for (ParIterator it = buffer()->par_iterator_begin();
111              it != end; ++it) {
112                 Paragraph * par = *it;
113                 // this has to be done before the delete
114                 if (par->autoDeleteInsets()) {
115                         found = true;
116 #ifdef WITH_WARNINGS
117 #warning FIXME
118 #endif
119                         // The test it.size()==1 was needed to prevent crashes.
120                         if (it.size() == 1) {
121                                 text->setCursor(this, cursor, par, 0);
122                                 text->redoParagraphs(this, cursor,
123                                                      cursor.par()->next());
124                                 text->fullRebreak(this);
125                         }
126                 }
127         }
128
129         // avoid forbidden cursor positions caused by error removing
130         if (tmpcursor.pos() > tmpcursor.par()->size())
131                 tmpcursor.pos(tmpcursor.par()->size());
132
133         text->setCursorIntern(this, tmpcursor.par(), tmpcursor.pos());
134
135         return found;
136 }
137
138
139 void BufferView::insertErrors(TeXErrors & terr)
140 {
141         // Save the cursor position
142         LyXCursor cursor = text->cursor;
143
144         for (TeXErrors::Errors::const_iterator cit = terr.begin();
145              cit != terr.end();
146              ++cit) {
147                 string const desctext(cit->error_desc);
148                 string const errortext(cit->error_text);
149                 string const msgtxt = desctext + '\n' + errortext;
150                 int const errorrow = cit->error_in_line;
151
152                 // Insert error string for row number
153                 int tmpid = -1; 
154                 int tmppos = -1;
155
156                 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
157                         buffer()->texrow.increasePos(tmpid, tmppos);
158                 }
159                 
160                 Paragraph * texrowpar = 0;
161
162                 if (tmpid == -1) {
163                         texrowpar = text->firstParagraph();
164                         tmppos = 0;
165                 } else {
166                         texrowpar = buffer()->getParFromID(tmpid);
167                 }
168
169                 if (texrowpar == 0)
170                         continue;
171
172                 InsetError * new_inset = new InsetError(msgtxt);
173                 text->setCursorIntern(this, texrowpar, tmppos);
174                 text->insertInset(this, new_inset);
175                 text->fullRebreak(this);
176         }
177         // Restore the cursor position
178         text->setCursorIntern(this, cursor.par(), cursor.pos());
179 }
180
181
182 void BufferView::setCursorFromRow(int row)
183 {
184         int tmpid = -1; 
185         int tmppos = -1;
186
187         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
188
189         Paragraph * texrowpar;
190
191         if (tmpid == -1) {
192                 texrowpar = text->firstParagraph();
193                 tmppos = 0;
194         } else {
195                 texrowpar = buffer()->getParFromID(tmpid);
196         }
197         text->setCursor(this, texrowpar, tmppos);
198 }
199
200
201 bool BufferView::insertInset(Inset * inset, string const & lout)
202 {
203         return pimpl_->insertInset(inset, lout);
204 }
205
206
207 /* This is also a buffer property (ale) */
208 // Not so sure about that. a goto Label function can not be buffer local, just
209 // think how this will work in a multiwindo/buffer environment, all the
210 // cursors in all the views showing this buffer will move. (Lgb)
211 // OK, then no cursor action should be allowed in buffer. (ale)
212 bool BufferView::gotoLabel(string const & label)
213
214 {
215         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
216              it != buffer()->inset_iterator_end(); ++it) {
217                 vector<string> labels = (*it)->getLabelList();
218                 if (find(labels.begin(),labels.end(),label)
219                      != labels.end()) {
220                         beforeChange(text);
221                         text->setCursor(this, it.getPar(), it.getPos());
222                         text->selection.cursor = text->cursor;
223                         update(text, BufferView::SELECT|BufferView::FITCUR);
224                         return true;
225                 }
226         }
227         return false;
228 }
229
230
231 void BufferView::menuUndo()
232 {
233         if (available()) {
234                 owner()->message(_("Undo"));
235                 hideCursor();
236                 beforeChange(text);
237                 update(text, BufferView::SELECT|BufferView::FITCUR);
238                 if (!textUndo(this))
239                         owner()->message(_("No further undo information"));
240                 else
241                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
242                 setState();
243         }
244 }
245
246
247 void BufferView::menuRedo()
248 {
249         if (theLockingInset()) {
250                 owner()->message(_("Redo not yet supported in math mode"));
251                 return;
252         }    
253    
254         if (available()) {
255                 owner()->message(_("Redo"));
256                 hideCursor();
257                 beforeChange(text);
258                 update(text, BufferView::SELECT|BufferView::FITCUR);
259                 if (!textRedo(this))
260                         owner()->message(_("No further redo information"));
261                 else
262                         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
263                 setState();
264         }
265 }
266
267
268 void BufferView::copyEnvironment()
269 {
270         if (available()) {
271                 text->copyEnvironmentType();
272                 owner()->message(_("Paragraph environment type copied"));
273         }
274 }
275
276
277 void BufferView::pasteEnvironment()
278 {
279         if (available()) {
280                 text->pasteEnvironmentType(this);
281                 owner()->message(_("Paragraph environment type set"));
282                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
283         }
284 }
285
286
287 void BufferView::copy()
288 {
289         if (available()) {
290                 text->copySelection(this);
291                 owner()->message(_("Copy"));
292         }
293 }
294
295
296 void BufferView::cut(bool realcut)
297 {
298         if (available()) {
299                 hideCursor();
300                 update(text, BufferView::SELECT|BufferView::FITCUR);
301                 text->cutSelection(this, true, realcut);
302                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
303                 owner()->message(_("Cut"));
304         }
305 }
306
307
308 void BufferView::paste()
309 {
310         if (!available()) return;
311
312         owner()->message(_("Paste"));
313
314         hideCursor();
315         // clear the selection
316         toggleSelection();
317         text->clearSelection();
318         update(text, BufferView::SELECT|BufferView::FITCUR);
319         
320         // paste
321         text->pasteSelection(this);
322         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
323         
324         // clear the selection 
325         toggleSelection();
326         text->clearSelection();
327         update(text, BufferView::SELECT|BufferView::FITCUR);
328 }
329
330
331 /* these functions are for the spellchecker */ 
332 string const BufferView::nextWord(float & value)
333 {
334         if (!available()) {
335                 value = 1;
336                 return string();
337         }
338
339         return text->selectNextWordToSpellcheck(this, value);
340 }
341
342   
343 void BufferView::selectLastWord()
344 {
345         if (!available()) return;
346    
347         LyXCursor cur = text->selection.cursor;
348         hideCursor();
349         beforeChange(text);
350         text->selection.cursor = cur;
351         text->selectSelectedWord(this);
352         toggleSelection(false);
353         update(text, BufferView::SELECT|BufferView::FITCUR);
354 }
355
356
357 void BufferView::endOfSpellCheck()
358 {
359         if (!available()) return;
360    
361         hideCursor();
362         beforeChange(text);
363         text->selectSelectedWord(this);
364         text->clearSelection();
365         update(text, BufferView::SELECT|BufferView::FITCUR);
366 }
367
368
369 void BufferView::replaceWord(string const & replacestring)
370 {
371         if (!available()) return;
372
373         LyXText * tt = getLyXText();
374         hideCursor();
375         update(tt, BufferView::SELECT|BufferView::FITCUR);
376    
377         /* clear the selection (if there is any) */ 
378         toggleSelection(false);
379         update(tt, BufferView::SELECT|BufferView::FITCUR);
380    
381         /* clear the selection (if there is any) */ 
382         toggleSelection(false);
383         tt->replaceSelectionWithString(this, replacestring);
384    
385         tt->setSelectionOverString(this, replacestring);
386
387         // Go back so that replacement string is also spellchecked
388         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
389                 tt->cursorLeft(this);
390         }
391         update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
392 }
393 // End of spellchecker stuff
394
395
396 bool BufferView::lockInset(UpdatableInset * inset)
397 {
398         // don't relock if we're already locked
399         if (theLockingInset() == inset)
400                 return true;
401         if (!theLockingInset() && inset) {
402                 theLockingInset(inset);
403                 return true;
404         } else if (inset) {
405             return theLockingInset()->lockInsetInInset(this, inset);
406         }
407         return false;
408 }
409
410
411 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
412 {
413         if (available() && theLockingInset()) {
414                 LyXCursor cursor = text->cursor;
415                 Inset * locking_inset = theLockingInset()->getLockingInset();
416
417                 if ((cursor.pos() - 1 >= 0) &&
418                     cursor.par()->isInset(cursor.pos() - 1) &&
419                     (cursor.par()->getInset(cursor.pos() - 1) ==
420                      locking_inset))
421                         text->setCursor(this, cursor,
422                                         cursor.par(), cursor.pos() - 1);
423                 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
424                 LyXText * txt = getLyXText();
425                 if (locking_inset->isTextInset() &&
426                     locking_inset->lyxCode() != Inset::ERT_CODE &&
427                     (txt->real_current_font.language() !=
428                      buffer()->params.language
429                      || txt->real_current_font.isVisibleRightToLeft()
430                      != buffer()->params.language->RightToLeft()))
431                         shape = (txt->real_current_font.isVisibleRightToLeft())
432                                 ? LyXScreen::REVERSED_L_SHAPE
433                                 : LyXScreen::L_SHAPE;
434                 y += cursor.y() + theLockingInset()->insetInInsetY();
435                 pimpl_->screen_->showManualCursor(text, x, y, asc, desc,
436                                                   shape);
437         }
438 }
439
440
441 void BufferView::hideLockedInsetCursor()
442 {
443         if (theLockingInset() && available()) {
444                 pimpl_->screen_->hideCursor();
445         }
446 }
447
448
449 void BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
450 {
451         if (theLockingInset() && available()) {
452                 y += text->cursor.y() + theLockingInset()->insetInInsetY();
453                 if (pimpl_->screen_->fitManualCursor(text, this, x, y, asc, desc))
454                         updateScrollbar();
455         }
456 }
457
458
459 int BufferView::unlockInset(UpdatableInset * inset)
460 {
461         if (inset && theLockingInset() == inset) {
462                 inset->insetUnlock(this);
463                 theLockingInset(0);
464                 // make sure we update the combo !
465                 owner()->setLayout(getLyXText()->cursor.par()->getLayout());
466                 finishUndo();
467                 return 0;
468         } else if (inset && theLockingInset() &&
469                    theLockingInset()->unlockInsetInInset(this, inset)) {
470                 // owner inset has updated the layout combo 
471                 finishUndo();
472                 return 0;
473         }
474         return bufferlist.unlockInset(inset);
475 }
476
477
478 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
479 {
480         if (!theLockingInset())
481                 return; // shouldn't happen
482         if (kind == Undo::EDIT) // in this case insets would not be stored!
483                 kind = Undo::FINISH;
484         setUndo(this, kind,
485                 text->cursor.par(),
486                 text->cursor.par()->next());
487 }
488
489
490 void BufferView::updateInset(Inset * inset, bool mark_dirty)
491 {
492         pimpl_->updateInset(inset, mark_dirty);
493 }
494
495
496 bool BufferView::ChangeInsets(Inset::Code code,
497                               string const & from, string const & to)
498 {
499         bool need_update = false;
500         LyXCursor cursor = text->cursor;
501         LyXCursor tmpcursor = cursor;
502         cursor.par(tmpcursor.par());
503         cursor.pos(tmpcursor.pos());
504
505         ParIterator end = buffer()->par_iterator_end();
506         for (ParIterator it = buffer()->par_iterator_begin();
507              it != end; ++it) {
508                 Paragraph * par = *it;
509                 bool changed_inset = false;
510                 for (Paragraph::inset_iterator it2 = par->inset_iterator_begin();
511                      it2 != par->inset_iterator_end(); ++it2) {
512                         if ((*it2)->lyxCode() == code) {
513                                 InsetCommand * inset = static_cast<InsetCommand *>(*it2);
514                                 if (inset->getContents() == from) {
515                                         inset->setContents(to);
516                                         changed_inset = true;
517                                 }
518                         }
519                 }
520                 if (changed_inset) {
521                         need_update = true;
522 #ifdef WITH_WARNINGS
523 #warning FIXME
524 #endif
525                         // The test it.size()==1 was needed to prevent crashes.
526                         // How to set the cursor corretly when it.size()>1 ??
527                         if (it.size() == 1) {
528                                 text->setCursorIntern(this, par, 0);
529                                 text->redoParagraphs(this, text->cursor,
530                                                      text->cursor.par()->next());
531                                 text->fullRebreak(this);
532                         }
533                 }
534         }
535         text->setCursorIntern(this, cursor.par(), cursor.pos());
536         return need_update;
537 }
538
539
540 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
541 {
542         // Check if the label 'from' appears more than once
543         vector<string> labels = buffer()->getLabelList();
544         if (count(labels.begin(), labels.end(), from) > 1)
545                 return false;
546
547         return ChangeInsets(Inset::REF_CODE, from, to);
548 }
549
550
551 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
552 {
553
554         vector<pair<string,string> > keys = buffer()->getBibkeyList();  
555         if (count_if(keys.begin(), keys.end(), 
556                      lyx::equal_1st_in_pair<string,string>(from)) 
557             > 1)
558                 return false;
559
560         return ChangeInsets(Inset::CITE_CODE, from, to);
561 }
562
563
564 UpdatableInset * BufferView::theLockingInset() const
565 {
566         // If NULL is not allowed we should put an Assert here. (Lgb)
567         if (text)
568                 return text->the_locking_inset;
569         return 0;
570 }
571
572
573 void BufferView::theLockingInset(UpdatableInset * inset)
574 {
575         text->the_locking_inset = inset;
576 }
577
578
579 LyXText * BufferView::getLyXText() const
580 {
581         if (theLockingInset()) {
582                 LyXText * txt = theLockingInset()->getLyXText(this, true);
583                 if (txt)
584                         return txt;
585         }
586         return text;
587 }
588
589
590 LyXText * BufferView::getParentText(Inset * inset) const
591 {
592         if (inset->owner()) {
593                 LyXText * txt = inset->getLyXText(this);
594                 inset = inset->owner();
595                 while (inset && inset->getLyXText(this) == txt)
596                         inset = inset->owner();
597                 if (inset)
598                         return inset->getLyXText(this);
599         }
600         return text;
601 }
602
603
604 Language const * BufferView::getParentLanguage(Inset * inset) const
605 {
606         LyXText * text = getParentText(inset);
607         return text->cursor.par()->getFontSettings(buffer()->params,
608                                                    text->cursor.pos()).language();
609 }