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