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