1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich,
7 * Copyright 1995-2001 The LyX Team.
9 * ====================================================== */
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
19 #include "lastfiles.h"
23 #include "BufferView.h"
26 #include "insets/insetlabel.h"
28 #include "frontends/lyx_gui.h"
29 #include "frontends/LyXView.h"
30 #include "frontends/Alert.h"
31 #include "frontends/FileDialog.h"
33 #include "support/FileInfo.h"
34 #include "support/filetools.h"
35 #include "support/forkedcall.h"
36 #include "support/path.h"
37 #include "support/systemcall.h"
38 #include "support/lstrings.h"
50 using std::back_inserter;
51 using std::istream_iterator;
55 extern BufferList bufferlist;
56 // this should be static, but I need it in buffer.C
57 bool quitting; // flag, that we are quitting the program
60 void ShowMessage(Buffer const * buf,
66 && buf && buf->getUser() && buf->getUser()->owner()) {
67 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
68 buf->getUser()->owner()->message(str);
70 lyxerr << msg1 << msg2 << msg3 << endl;
78 bool MenuWrite(BufferView * bv, Buffer * buffer)
81 lastfiles->newFile(buffer->fileName());
85 // FIXME: we don't tell the user *WHY* the save failed !!
87 string const file = MakeDisplayPath(buffer->fileName(), 30);
89 string text = bformat(_("The document %1$s could not be saved.\n\n"
90 "Do you want to rename the document and try again?"), file);
91 int const ret = Alert::prompt(_("Rename and save?"),
92 text, 0, 1, _("&Rename"), _("&Cancel"));
95 return WriteAs(bv, buffer);
101 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
103 string fname = buffer->fileName();
104 string const oldname = fname;
106 if (filename.empty()) {
108 FileDialog fileDlg(_("Choose a filename to save document as"),
110 make_pair(string(_("Documents|#o#O")),
111 string(lyxrc.document_path)),
112 make_pair(string(_("Templates|#T#t")),
113 string(lyxrc.template_path)));
115 if (!IsLyXFilename(fname))
118 FileDialog::Result result =
119 fileDlg.save(OnlyPath(fname),
120 _("*.lyx| LyX Documents (*.lyx)"),
121 OnlyFilename(fname));
123 if (result.first == FileDialog::Later)
126 fname = result.second;
131 // Make sure the absolute filename ends with appropriate suffix
132 fname = MakeAbsPath(fname);
133 if (!IsLyXFilename(fname))
138 FileInfo const myfile(fname);
140 string const file = MakeDisplayPath(fname, 30);
141 string text = bformat(_("The document %1$s already exists.\n\n"
142 "Do you want to over-write that document?"), file);
143 int const ret = Alert::prompt(_("Over-write document?"),
144 text, 0, 1, _("&Over-write"), _("&Cancel"));
150 // Ok, change the name of the buffer
151 buffer->setFileName(fname);
153 bool unnamed = buffer->isUnnamed();
154 buffer->setUnnamed(false);
156 if (!MenuWrite(bv, buffer)) {
157 buffer->setFileName(oldname);
158 buffer->setUnnamed(unnamed);
162 removeAutosaveFile(oldname);
169 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
171 if (lyx_gui::use_gui) {
172 if (!bufferlist.quitWriteAll())
175 lastfiles->writeFile(lyxrc.lastfiles);
178 // Set a flag that we do quitting from the program,
179 // so no refreshes are necessary.
182 // close buffers first
183 bufferlist.closeAll();
185 // do any other cleanup procedures now
186 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
188 if (destroyDir(system_tempdir) != 0) {
189 string msg = bformat(_("Could not remove the temporary directory %1$s"),
191 Alert::warning(_("Could not remove temporary directory"), msg);
200 class AutoSaveBuffer : public ForkedProcess {
203 AutoSaveBuffer(BufferView & bv, string const & fname)
204 : bv_(bv), fname_(fname) {}
206 virtual ForkedProcess * clone() const {
207 return new AutoSaveBuffer(*this);
213 virtual int generateChild();
220 int AutoSaveBuffer::start()
222 command_ = bformat(_("Auto-saving %1$s"), fname_);
223 return runNonBlocking();
227 int AutoSaveBuffer::generateChild()
229 // tmp_ret will be located (usually) in /tmp
230 // will that be a problem?
231 pid_t const pid = fork(); // If you want to debug the autosave
232 // you should set pid to -1, and comment out the
234 if (pid == 0 || pid == -1) {
235 // pid = -1 signifies that lyx was unable
236 // to fork. But we will do the save
240 string const tmp_ret = lyx::tempName(string(), "lyxauto");
241 if (!tmp_ret.empty()) {
242 bv_.buffer()->writeFile(tmp_ret);
243 // assume successful write of tmp_ret
244 if (!lyx::rename(tmp_ret, fname_)) {
246 // most likely couldn't move between filesystems
247 // unless write of tmp_ret failed
248 // so remove tmp file (if it exists)
249 lyx::unlink(tmp_ret);
256 // failed to write/rename tmp_ret so try writing direct
257 if (!bv_.buffer()->writeFile(fname_)) {
258 // It is dangerous to do this in the child,
259 // but safe in the parent, so...
261 bv_.owner()->message(_("Autosave failed!"));
264 if (pid == 0) { // we are the child so...
274 void AutoSave(BufferView * bv)
275 // should probably be moved into BufferList (Lgb)
276 // Perfect target for a thread...
278 if (!bv->available())
281 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
282 // We don't save now, but we'll try again later
283 bv->owner()->resetAutosaveTimer();
287 bv->owner()->message(_("Autosaving current document..."));
289 // create autosave filename
290 string fname = bv->buffer()->filePath();
292 fname += OnlyFilename(bv->buffer()->fileName());
295 AutoSaveBuffer autosave(*bv, fname);
298 bv->buffer()->markBakClean();
299 bv->owner()->resetAutosaveTimer();
304 // Copyright CHT Software Service GmbH
307 // create new file with template
310 Buffer * NewFile(string const & filename)
312 // Split argument by :
314 string tmpname = split(filename, name, ':');
315 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
316 if (name.length() == 1
317 && isalpha(static_cast<unsigned char>(name[0]))
318 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
320 name += token(tmpname, ':', 0);
321 tmpname = split(tmpname, ':');
324 lyxerr[Debug::INFO] << "Arg is " << filename
325 << "\nName is " << name
326 << "\nTemplate is " << tmpname << endl;
328 // find a free buffer
329 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
331 lastfiles->newFile(tmpbuf->fileName());
336 // Insert ascii file (if filename is empty, prompt for one)
337 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
339 if (!bv->available())
342 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
346 // clear the selection
347 bool flag = (bv->text == bv->getLyXText());
349 bv->beforeChange(bv->text);
351 bv->getLyXText()->insertStringAsLines(tmpstr);
353 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
355 bv->update(BufferView::SELECT);
359 // Insert ascii file (if filename is empty, prompt for one)
360 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
365 FileDialog fileDlg(_("Select file to insert"),
366 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
368 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
370 if (result.first == FileDialog::Later)
373 fname = result.second;
381 if (!fi.readable()) {
382 string const error = strerror(errno);
383 string const file = MakeDisplayPath(fname, 50);
384 string const text = bformat(_("Could not read the specified document\n"
385 "%1$s\ndue to the error: %2$s"), file, error);
386 Alert::error(_("Could not read file"), text);
390 ifstream ifs(fname.c_str());
392 string const error = strerror(errno);
393 string const file = MakeDisplayPath(fname, 50);
394 string const text = bformat(_("Could not open the specified document\n"
395 "%1$s\ndue to the error: %2$s"), file, error);
396 Alert::error(_("Could not open file"), text);
400 ifs.unsetf(ios::skipws);
401 istream_iterator<char> ii(ifs);
402 istream_iterator<char> end;
403 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
404 // We use this until the compilers get better...
406 copy(ii, end, back_inserter(tmp));
407 string const tmpstr(tmp.begin(), tmp.end());
409 // This is what we want to use and what we will use once the
410 // compilers get good enough.
411 //string tmpstr(ii, end); // yet a reason for using std::string
412 // alternate approach to get the file into a string:
414 copy(ii, end, back_inserter(tmpstr));
421 string const getPossibleLabel(BufferView const & bv)
423 Paragraph * par = &*bv.getLyXText()->cursor.par();
424 LyXLayout_ptr layout = par->layout();
425 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
426 Paragraph * par2 = par->previous();
428 LyXLayout_ptr const & layout2 = par2->layout();
430 if (layout2->latextype != LATEX_PARAGRAPH) {
436 string text = layout->latexname().substr(0, 3);
437 if (layout->latexname() == "theorem")
438 text = "thm"; // Create a correct prefix for prettyref
441 if (layout->latextype == LATEX_PARAGRAPH ||
442 lyxrc.label_init_length < 0)
445 string par_text = par->asString(bv.buffer(), false);
446 for (int i = 0; i < lyxrc.label_init_length; ++i) {
447 if (par_text.empty())
450 par_text = split(par_text, head, ' ');
452 text += '-'; // Is it legal to use spaces in
461 // This function runs "configure" and then rereads lyx.defaults to
462 // reconfigure the automatic settings.
463 void Reconfigure(BufferView * bv)
465 bv->owner()->message(_("Running configure..."));
467 // Run configure in user lyx directory
470 one.startscript(Systemcall::Wait,
471 AddName(system_lyxdir, "configure"));
473 bv->owner()->message(_("Reloading configuration..."));
474 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
476 Alert::information(_("System reconfigured"),
477 _("The system has been reconfigured.\n"
478 "You need to restart LyX to make use of any \n"
479 "updated document class specifications."));