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