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"
25 #include "insets/insetlabel.h"
27 #include "frontends/lyx_gui.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
32 #include "support/FileInfo.h"
33 #include "support/filetools.h"
34 #include "support/forkedcall.h"
35 #include "support/path.h"
36 #include "support/systemcall.h"
37 #include "support/lstrings.h"
39 #include "BoostFormat.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;
81 // should be moved to lyxfunc.C
82 bool MenuWrite(BufferView * bv, Buffer * buffer)
84 if (!buffer->save()) {
85 if (Alert::askQuestion(_("Save failed. Rename and try again?"),
86 MakeDisplayPath(buffer->fileName(), 50),
87 _("(If not, document is not saved.)"))) {
88 return WriteAs(bv, buffer);
92 lastfiles->newFile(buffer->fileName());
98 // should be moved to BufferView.C
99 // Half of this func should be in LyXView, the rest in BufferView.
100 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
102 string fname = buffer->fileName();
103 string const oldname = fname;
105 if (filename.empty()) {
107 FileDialog fileDlg(bv->owner(),
108 _("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 // Same name as we have already?
139 if (!buffer->isUnnamed() && fname == oldname) {
140 if (!Alert::askQuestion(_("Same name as document already has:"),
141 MakeDisplayPath(fname, 50),
144 // Falls through to name change and save
146 // No, but do we have another file with this name open?
147 else if (!buffer->isUnnamed() && bufferlist.exists(fname)) {
148 if (Alert::askQuestion(_("Another document with same name open!"),
149 MakeDisplayPath(fname, 50),
150 _("Replace with current document?")))
152 bufferlist.close(bufferlist.getBuffer(fname));
154 // Ok, change the name of the buffer, but don't save!
155 buffer->setFileName(fname);
158 ShowMessage(buffer, _("Document renamed to '"),
159 MakeDisplayPath(fname), _("', but not saved..."));
162 } // Check whether the file exists
164 FileInfo const myfile(fname);
165 if (myfile.isOK() && !Alert::askQuestion(_("Document already exists:"),
166 MakeDisplayPath(fname, 50),
171 // Ok, change the name of the buffer
172 buffer->setFileName(fname);
174 bool unnamed = buffer->isUnnamed();
175 buffer->setUnnamed(false);
177 if (!MenuWrite(bv, buffer)) {
178 buffer->setFileName(oldname);
179 buffer->setUnnamed(unnamed);
180 ShowMessage(buffer, _("Document could not be saved!"),
181 _("Holding the old name."), MakeDisplayPath(oldname));
184 // now remove the oldname autosave file if existant!
185 removeAutosaveFile(oldname);
190 int MenuRunChktex(Buffer * buffer)
194 if (buffer->isSGML()) {
195 Alert::alert(_("Chktex does not work with SGML derived documents."));
198 ret = buffer->runChktex();
204 s = _("No warnings found.");
205 } else if (ret == 1) {
206 s = _("One warning found.");
207 t = _("Use `Navigate->Error' to find it.");
210 s += _(" warnings found.");
211 t = _("Use `Navigate->Error' to find them.");
213 Alert::alert(_("Chktex run successfully"), s, t);
215 Alert::alert(_("Error!"), _("It seems chktex does not work."));
223 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
226 if (!bufferlist.qwriteAll())
229 lastfiles->writeFile(lyxrc.lastfiles);
232 // Set a flag that we do quitting from the program,
233 // so no refreshes are necessary.
236 // close buffers first
237 bufferlist.closeAll();
239 // do any other cleanup procedures now
240 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
242 DestroyLyXTmpDir(system_tempdir);
250 class AutoSaveBuffer : public ForkedProcess {
253 AutoSaveBuffer(BufferView & bv, string const & fname)
254 : bv_(bv), fname_(fname) {}
256 virtual ForkedProcess * clone() const {
257 return new AutoSaveBuffer(*this);
263 virtual int generateChild();
270 int AutoSaveBuffer::start()
273 command_ = boost::io::str(boost::format(_("Auto-saving %1$s")) % fname_);
275 command_ = _("Auto-saving ") + fname_;
277 return runNonBlocking();
281 int AutoSaveBuffer::generateChild()
283 // tmp_ret will be located (usually) in /tmp
284 // will that be a problem?
285 pid_t const pid = fork(); // If you want to debug the autosave
286 // you should set pid to -1, and comment out the
288 if (pid == 0 || pid == -1) {
289 // pid = -1 signifies that lyx was unable
290 // to fork. But we will do the save
294 string const tmp_ret = lyx::tempName(string(), "lyxauto");
295 if (!tmp_ret.empty()) {
296 bv_.buffer()->writeFile(tmp_ret);
297 // assume successful write of tmp_ret
298 if (!lyx::rename(tmp_ret, fname_)) {
300 // most likely couldn't move between filesystems
301 // unless write of tmp_ret failed
302 // so remove tmp file (if it exists)
303 lyx::unlink(tmp_ret);
310 // failed to write/rename tmp_ret so try writing direct
311 if (!bv_.buffer()->writeFile(fname_)) {
312 // It is dangerous to do this in the child,
313 // but safe in the parent, so...
315 bv_.owner()->message(_("Autosave failed!"));
318 if (pid == 0) { // we are the child so...
328 void AutoSave(BufferView * bv)
329 // should probably be moved into BufferList (Lgb)
330 // Perfect target for a thread...
332 if (!bv->available())
335 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
336 // We don't save now, but we'll try again later
337 bv->owner()->resetAutosaveTimer();
341 bv->owner()->message(_("Autosaving current document..."));
343 // create autosave filename
344 string fname = bv->buffer()->filePath();
346 fname += OnlyFilename(bv->buffer()->fileName());
349 AutoSaveBuffer autosave(*bv, fname);
352 bv->buffer()->markBakClean();
353 bv->owner()->resetAutosaveTimer();
358 // Copyright CHT Software Service GmbH
361 // create new file with template
364 Buffer * NewFile(string const & filename)
366 // Split argument by :
368 string tmpname = split(filename, name, ':');
369 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
370 if (name.length() == 1
371 && isalpha(static_cast<unsigned char>(name[0]))
372 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
374 name += token(tmpname, ':', 0);
375 tmpname = split(tmpname, ':');
378 lyxerr[Debug::INFO] << "Arg is " << filename
379 << "\nName is " << name
380 << "\nTemplate is " << tmpname << endl;
382 // find a free buffer
383 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
385 lastfiles->newFile(tmpbuf->fileName());
390 // Insert ascii file (if filename is empty, prompt for one)
391 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
393 if (!bv->available())
396 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
403 // clear the selection
404 bool flag = (bv->text == bv->getLyXText());
406 bv->beforeChange(bv->text);
408 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
410 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
413 BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
417 // Insert ascii file (if filename is empty, prompt for one)
418 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
423 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
424 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
426 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
428 if (result.first == FileDialog::Later)
431 fname = result.second;
439 if (!fi.readable()) {
440 Alert::err_alert(_("Error! Specified file is unreadable: "),
441 MakeDisplayPath(fname, 50));
445 ifstream ifs(fname.c_str());
447 Alert::err_alert(_("Error! Cannot open specified file: "),
448 MakeDisplayPath(fname, 50));
452 ifs.unsetf(ios::skipws);
453 istream_iterator<char> ii(ifs);
454 istream_iterator<char> end;
455 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
456 // We use this until the compilers get better...
458 copy(ii, end, back_inserter(tmp));
459 string const tmpstr(tmp.begin(), tmp.end());
461 // This is what we want to use and what we will use once the
462 // compilers get good enough.
463 //string tmpstr(ii, end); // yet a reason for using std::string
464 // alternate approach to get the file into a string:
466 copy(ii, end, back_inserter(tmpstr));
473 void MenuInsertLabel(BufferView * bv, string const & arg)
476 bv->owner()->prohibitInput();
478 Paragraph * par = bv->getLyXText()->cursor.par();
479 LyXLayout_ptr layout = par->layout();
480 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
481 Paragraph * par2 = par->previous();
483 LyXLayout_ptr const & layout2 = par2->layout();
485 if (layout2->latextype != LATEX_PARAGRAPH) {
490 string text = layout->latexname().substr(0, 3);
491 if (layout->latexname() == "theorem")
492 text = "thm"; // Create a correct prefix for prettyref
495 if (layout->latextype == LATEX_PARAGRAPH ||
496 lyxrc.label_init_length < 0)
498 string par_text = par->asString(bv->buffer(), false);
499 for (int i = 0; i < lyxrc.label_init_length; ++i) {
500 if (par_text.empty())
503 par_text = split(par_text, head, ' ');
505 text += '-'; // Is it legal to use spaces in
510 pair<bool, string> result =
511 Alert::askForText(_("Enter new label to insert:"), text);
513 label = trim(result.second);
516 if (!label.empty()) {
517 InsetCommandParams p("label", label);
518 InsetLabel * inset = new InsetLabel(p);
519 bv->insertInset(inset);
521 bv->owner()->allowInput();
525 // This function runs "configure" and then rereads lyx.defaults to
526 // reconfigure the automatic settings.
527 void Reconfigure(BufferView * bv)
529 bv->owner()->message(_("Running configure..."));
531 // Run configure in user lyx directory
534 one.startscript(Systemcall::Wait,
535 AddName(system_lyxdir, "configure"));
537 bv->owner()->message(_("Reloading configuration..."));
538 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
539 Alert::alert(_("The system has been reconfigured."),
540 _("You need to restart LyX to make use of any"),
541 _("updated document class specifications."));