]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
Fixed cut&paste bugs and added freespacing for ERT Insets.
[lyx.git] / src / bufferlist.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Word Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team. 
8  *
9  *           This file is Copyright 1996-2001
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #ifdef __GNUG__
16 #pragma implementation
17 #endif
18
19 #include <config.h>
20
21 #include <assert.h>
22 #include <algorithm>
23 #include <functional>
24
25 #include "frontends/Alert.h"
26 #include "bufferlist.h"
27 #include "lyx_main.h"
28 #include "support/FileInfo.h"
29 #include "support/filetools.h"
30 #include "support/lyxmanip.h"
31 #include "support/lyxfunctional.h"
32 #include "support/LAssert.h"
33 #include "lyx_gui_misc.h"
34 #include "lastfiles.h"
35 #include "debug.h"
36 #include "lyxrc.h"
37 #include "lyxtext.h"
38 #include "lyx_cb.h"
39 #include "bufferview_funcs.h"
40 #include "BufferView.h"
41 #include "gettext.h"
42 #include "LyXView.h"
43 #include "vc-backend.h"
44 #include "TextCache.h"
45
46 using std::vector;
47 using std::find;
48 using std::endl;
49 using std::find_if;
50 using std::for_each;
51 using std::mem_fun;
52
53 extern BufferView * current_view;
54
55 //
56 // Class BufferStorage
57 //
58
59 void BufferStorage::release(Buffer * buf)
60 {
61         lyx::Assert(buf);
62         Container::iterator it = find(container.begin(), container.end(), buf);
63         if (it != container.end()) {
64                 // Make sure that we don't store a LyXText in
65                 // the textcache that points to the buffer
66                 // we just deleted.
67                 Buffer * tmp = (*it);
68                 container.erase(it);
69                 textcache.removeAllWithBuffer(tmp);
70                 delete tmp;
71         }
72 }
73
74
75 Buffer * BufferStorage::newBuffer(string const & s, bool ronly)
76 {
77         Buffer * tmpbuf = new Buffer(s, ronly);
78         tmpbuf->params.useClassDefaults();
79         lyxerr[Debug::INFO] << "Assigning to buffer "
80                             << container.size() << endl;
81         container.push_back(tmpbuf);
82         return tmpbuf;
83 }
84
85
86 //
87 // Class BufferList
88 //
89
90 BufferList::BufferList()
91         : state_(BufferList::OK)
92 {}
93
94
95 bool BufferList::empty() const
96 {
97         return bstore.empty();
98 }
99
100
101 bool BufferList::qwriteOne(Buffer * buf, string const & fname, string & unsaved_list)
102 {
103         bool reask = true;
104         while (reask) {
105                 switch (Alert::askConfirmation(_("Changes in document:"),
106                                        fname,
107                                        _("Save document?"))) {
108                 case 1: // Yes
109                         // FIXME: WriteAs can be asynch !
110                         if (buf->isUnnamed())
111                                 reask = !WriteAs(current_view, buf);
112                         else {
113                                 reask = !MenuWrite(current_view, buf);
114                         }
115                         break;
116                 case 2: // No
117                         // if we crash after this we could
118                         // have no autosave file but I guess
119                         // this is really inprobable (Jug)
120                         if (buf->isUnnamed()) {
121                                 removeAutosaveFile(buf->fileName());
122                         }
123  
124                         unsaved_list += MakeDisplayPath(fname, 50) + "\n";
125                         return true;
126                 case 3: // Cancel
127                         return false;
128                 }
129         }
130         return true;
131 }
132
133  
134 bool BufferList::qwriteAll()
135 {
136         string unsaved;
137         for (BufferStorage::iterator it = bstore.begin();
138              it != bstore.end(); ++it)
139         {
140                 if (!(*it)->isLyxClean()) {
141                         string fname;
142                         if ((*it)->isUnnamed())
143                                 fname = OnlyFilename((*it)->fileName());
144                         else
145                                 fname = MakeDisplayPath((*it)->fileName(), 50);
146                         if (!qwriteOne(*it, fname, unsaved)) // cancel the request!
147                                 return false;
148                 }
149         }
150  
151         if (!unsaved.empty() && lyxrc.exit_confirmation) {
152                 return Alert::askQuestion(_("Some documents were not saved:"),
153                                           unsaved, _("Exit anyway?"));
154         }
155
156         return true;
157 }
158
159
160 void BufferList::closeAll()
161 {
162         state_ = BufferList::CLOSING;
163         // Since we are closing we can just as well delete all
164         // in the textcache this will also speed the closing/quiting up a bit.
165         textcache.clear();
166         
167         while (!bstore.empty()) {
168                 close(bstore.front());
169         }
170         state_ = BufferList::OK;
171 }
172
173
174 bool BufferList::close(Buffer * buf)
175 {
176         lyx::Assert(buf);
177         
178         // CHECK
179         // Trace back why we need to use buf->getUser here.
180         // Perhaps slight rewrite is in order? (Lgb)
181         
182         if (buf->getUser()) buf->getUser()->insetUnlock();
183         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
184                 if (buf->getUser())
185                         buf->getUser()->owner()->prohibitInput();
186                 string fname;
187                 if (buf->isUnnamed())
188                         fname = OnlyFilename(buf->fileName());
189                 else
190                         fname = MakeDisplayPath(buf->fileName(), 50);
191                 bool reask = true;
192                 while (reask) {
193                         switch (Alert::askConfirmation(_("Changes in document:"),
194                                                fname,
195                                                _("Save document?"))){
196                         case 1: // Yes
197                                 if (buf->isUnnamed())
198                                         reask = !WriteAs(current_view, buf);
199                                 else if (buf->save()) {
200                                         lastfiles->newFile(buf->fileName());
201                                         reask = false;
202                                 } else {
203                                         if (buf->getUser())
204                                                 buf->getUser()->owner()->allowInput();
205                                         return false;
206                                 }
207                                 break;
208                         case 2:
209                                 if (buf->isUnnamed()) {
210                                         removeAutosaveFile(buf->fileName());
211                                 }
212                                 reask = false;
213                                 break;
214                         case 3: // Cancel
215                                 if (buf->getUser())
216                                         buf->getUser()->owner()->allowInput();
217                                 return false;
218                         }
219                 }
220                 if (buf->getUser())
221                         buf->getUser()->owner()->allowInput();
222         }
223
224         bstore.release(buf);
225         return true;
226 }
227
228
229 vector<string> const BufferList::getFileNames() const
230 {
231         vector<string> nvec;
232         std::copy(bstore.begin(), bstore.end(),
233                   lyx::back_inserter_fun(nvec, &Buffer::fileName));
234         return nvec;
235 }
236
237
238 Buffer * BufferList::first()
239 {
240         if (bstore.empty()) return 0;
241         return bstore.front();
242 }
243
244
245 Buffer * BufferList::getBuffer(unsigned int choice)
246 {
247         if (choice >= bstore.size()) return 0;
248         return bstore[choice];
249 }
250
251
252 int BufferList::unlockInset(UpdatableInset * inset)
253 {
254         lyx::Assert(inset);
255         
256         //if (!inset) return 1;
257         for (BufferStorage::iterator it = bstore.begin();
258              it != bstore.end(); ++it) {
259                 if ((*it)->getUser()
260                     && (*it)->getUser()->theLockingInset() == inset) {
261                         (*it)->getUser()->insetUnlock();
262                         return 0;
263                 }
264         }
265         return 1;
266 }
267
268
269 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
270 {
271         for (BufferStorage::iterator it = bstore.begin();
272              it != bstore.end(); ++it) {
273                 if (!(*it)->isDepClean(mastertmpdir)) {
274                         string writefile = mastertmpdir;
275                         writefile += '/';
276                         writefile += (*it)->getLatexName();
277                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
278                                              false, true);
279                         (*it)->markDepClean(mastertmpdir);
280                 }
281         }
282 }
283
284
285 void BufferList::emergencyWriteAll()
286 {
287         for_each(bstore.begin(), bstore.end(),
288                  lyx::class_fun(*this, &BufferList::emergencyWrite));
289 }
290
291
292 void BufferList::emergencyWrite(Buffer * buf) 
293 {
294         // assert(buf) // this is not good since C assert takes an int
295                        // and a pointer is a long (JMarc)
296         assert(buf != 0); // use c assert to avoid a loop
297
298         
299         // No need to save if the buffer has not changed.
300         if (buf->isLyxClean()) return;
301         
302         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
303                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
304                       : buf->fileName().c_str()) << endl;
305         
306         // We try to save three places:
307
308         // 1) Same place as document. Unless it is an unnamed doc.
309         if (!buf->isUnnamed()) {
310                 string s = buf->fileName();
311                 s += ".emergency";
312                 lyxerr << "  " << s << endl;
313                 if (buf->writeFile(s, true)) {
314                         buf->markLyxClean();
315                         lyxerr << _("  Save seems successful. Phew.") << endl;
316                         return;
317                 } else {
318                         lyxerr << _("  Save failed! Trying...") << endl;
319                 }
320         }
321         
322         // 2) In HOME directory.
323         string s = AddName(GetEnvPath("HOME"), buf->fileName());
324         s += ".emergency";
325         lyxerr << " " << s << endl;
326         if (buf->writeFile(s, true)) {
327                 buf->markLyxClean();
328                 lyxerr << _("  Save seems successful. Phew.") << endl;
329                 return;
330         }
331         
332         lyxerr << _("  Save failed! Trying...") << endl;
333         
334         // 3) In "/tmp" directory.
335         // MakeAbsPath to prepend the current
336         // drive letter on OS/2
337         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
338         s += ".emergency";
339         lyxerr << " " << s << endl;
340         if (buf->writeFile(s, true)) {
341                 buf->markLyxClean();
342                 lyxerr << _("  Save seems successful. Phew.") << endl;
343                 return;
344         }
345         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
346 }
347
348
349
350 Buffer * BufferList::readFile(string const & s, bool ronly)
351 {
352         Buffer * b = bstore.newBuffer(s, ronly);
353
354         string ts = s;
355         string e = OnlyPath(s);
356         string a = e;
357         // File information about normal file
358         FileInfo fileInfo2(s);
359
360         if (!fileInfo2.exist()) {
361                 Alert::alert(_("Error!"), _("Cannot open file"), 
362                         MakeDisplayPath(s));
363                 return 0;
364         }
365  
366         // Check if emergency save file exists and is newer.
367         e += OnlyFilename(s) + ".emergency";
368         FileInfo fileInfoE(e);
369
370         bool use_emergency = false;
371
372         if (fileInfoE.exist() && fileInfo2.exist()) {
373                 if (fileInfoE.getModificationTime()
374                     > fileInfo2.getModificationTime()) {
375                         if (Alert::askQuestion(_("An emergency save of this document exists!"),
376                                         MakeDisplayPath(s, 50),
377                                         _("Try to load that instead?"))) {
378                                 ts = e;
379                                 // the file is not saved if we load the
380                                 // emergency file.
381                                 b->markDirty();
382                                 use_emergency = true;
383                         } else {
384                                 // Here, we should delete the emergency save
385                                 lyx::unlink(e);
386                         }
387                 }
388         }
389
390         if (!use_emergency) {
391                 // Now check if autosave file is newer.
392                 a += '#';
393                 a += OnlyFilename(s);
394                 a += '#';
395                 FileInfo fileInfoA(a);
396                 if (fileInfoA.exist() && fileInfo2.exist()) {
397                         if (fileInfoA.getModificationTime()
398                             > fileInfo2.getModificationTime()) {
399                                 if (Alert::askQuestion(_("Autosave file is newer."),
400                                                 MakeDisplayPath(s, 50),
401                                                 _("Load that one instead?"))) {
402                                         ts = a;
403                                         // the file is not saved if we load the
404                                         // autosave file.
405                                         b->markDirty();
406                                 } else {
407                                         // Here, we should delete the autosave
408                                         lyx::unlink(a);
409                                 }
410                         }
411                 }
412         }
413         // not sure if this is the correct place to begin LyXLex
414         LyXLex lex(0, 0);
415         lex.setFile(ts);
416         if (b->readFile(lex))
417                 return b;
418         else {
419                 bstore.release(b);
420                 return 0;
421         }
422 }
423
424
425 bool BufferList::exists(string const & s) const
426 {
427         return find_if(bstore.begin(), bstore.end(),
428                        lyx::compare_memfun(&Buffer::fileName, s))
429                 != bstore.end();
430 }
431
432
433 bool BufferList::isLoaded(Buffer const * b) const
434 {
435         lyx::Assert(b);
436         
437         BufferStorage::const_iterator cit =
438                 find(bstore.begin(), bstore.end(), b);
439         return cit != bstore.end();
440 }
441
442
443 Buffer * BufferList::getBuffer(string const & s)
444 {
445         BufferStorage::iterator it =
446                 find_if(bstore.begin(), bstore.end(),
447                         lyx::compare_memfun(&Buffer::fileName, s));
448         return it != bstore.end() ? (*it) : 0;
449 }
450
451
452 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
453 {
454         // get a free buffer
455         Buffer * b = bstore.newBuffer(name);
456
457         // use defaults.lyx as a default template if it exists.
458         if (tname.empty()) {
459                 tname = LibFileSearch("templates", "defaults.lyx");
460         }
461         if (!tname.empty()) {
462                 bool templateok = false;
463                 LyXLex lex(0, 0);
464                 lex.setFile(tname);
465                 if (lex.isOK()) {
466                         if (b->readFile(lex)) {
467                                 templateok = true;
468                         }
469                 }
470                 if (!templateok) {
471                         Alert::alert(_("Error!"), _("Unable to open template"), 
472                                    MakeDisplayPath(tname));
473                         // no template, start with empty buffer
474                         b->paragraph = new Paragraph;
475                 }
476         } else {  // start with empty buffer
477                 b->paragraph = new Paragraph;
478         }
479
480         if (!lyxrc.new_ask_filename && !isNamed) {
481                 b->setUnnamed();
482                 b->setFileName(name);
483         }
484
485         b->setReadonly(false);
486         
487         return b;
488 }
489
490
491 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
492 {
493         // get absolute path of file and add ".lyx" to the filename if
494         // necessary
495         string s = FileSearch(string(), filename, "lyx");
496         if (s.empty()) {
497                 s = filename;
498         }
499
500         // file already open?
501         if (exists(s)) {
502                 if (Alert::askQuestion(_("Document is already open:"), 
503                                 MakeDisplayPath(s, 50),
504                                 _("Do you want to reload that document?"))) {
505                         // Reload is accomplished by closing and then loading
506                         if (!close(getBuffer(s))) {
507                                 return 0;
508                         }
509                         // Fall through to new load. (Asger)
510                 } else {
511                         // Here, we pretend that we just loaded the 
512                         // open document
513                         return getBuffer(s);
514                 }
515         }
516         Buffer * b = 0;
517         bool ro = false;
518         switch (IsFileWriteable(s)) {
519         case 0:
520                 ro = true;
521                 // Fall through
522         case 1:
523                 b = readFile(s, ro);
524                 if (b) {
525                         b->lyxvc.file_found_hook(s);
526                 }
527                 break; //fine- it's r/w
528         case -1:
529                 // Here we probably should run
530                 if (LyXVC::file_not_found_hook(s)) {
531                         // Ask if the file should be checked out for
532                         // viewing/editing, if so: load it.
533                         if (Alert::askQuestion(_("Do you want to retrieve file under version control?"))) {
534                                 // How can we know _how_ to do the checkout?
535                                 // With the current VC support it has to be,
536                                 // a RCS file since CVS do not have special ,v files.
537                                 RCS::retrive(s);
538                                 return loadLyXFile(filename, tolastfiles);
539                         }
540                 }
541                 if (Alert::askQuestion(_("Cannot open specified file:"), 
542                                 MakeDisplayPath(s, 50),
543                                 _("Create new document with this name?")))
544                         {
545                                 // Find a free buffer
546                                 b = newFile(s, string(), true);
547                         }
548                 break;
549         }
550
551         if (b && tolastfiles)
552                 lastfiles->newFile(b->fileName());
553
554         return b;
555 }