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"
49 using std::back_inserter;
50 using std::istream_iterator;
54 extern BufferList bufferlist;
55 // this should be static, but I need it in buffer.C
56 bool quitting; // flag, that we are quitting the program
59 void ShowMessage(Buffer const * buf,
65 && buf && buf->getUser() && buf->getUser()->owner()) {
66 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
67 buf->getUser()->owner()->message(str);
69 lyxerr << msg1 << msg2 << msg3 << endl;
80 // should be moved to lyxfunc.C
81 bool MenuWrite(BufferView * bv, Buffer * buffer)
83 if (!buffer->save()) {
84 if (Alert::askQuestion(_("Save failed. Rename and try again?"),
85 MakeDisplayPath(buffer->fileName(), 50),
86 _("(If not, document is not saved.)"))) {
87 return WriteAs(bv, buffer);
91 lastfiles->newFile(buffer->fileName());
97 // should be moved to BufferView.C
98 // Half of this func should be in LyXView, the rest in BufferView.
99 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
101 string fname = buffer->fileName();
102 string const oldname = fname;
104 if (filename.empty()) {
106 FileDialog fileDlg(bv->owner(),
107 _("Choose a filename to save document as"),
109 make_pair(string(_("Documents|#o#O")),
110 string(lyxrc.document_path)),
111 make_pair(string(_("Templates|#T#t")),
112 string(lyxrc.template_path)));
114 if (!IsLyXFilename(fname))
117 FileDialog::Result result =
118 fileDlg.Select(OnlyPath(fname),
119 _("*.lyx|LyX Documents (*.lyx)"),
120 OnlyFilename(fname));
122 if (result.first == FileDialog::Later)
125 fname = result.second;
130 // Make sure the absolute filename ends with appropriate suffix
131 fname = MakeAbsPath(fname);
132 if (!IsLyXFilename(fname))
137 // Same name as we have already?
138 if (!buffer->isUnnamed() && fname == oldname) {
139 if (!Alert::askQuestion(_("Same name as document already has:"),
140 MakeDisplayPath(fname, 50),
143 // Falls through to name change and save
145 // No, but do we have another file with this name open?
146 else if (!buffer->isUnnamed() && bufferlist.exists(fname)) {
147 if (Alert::askQuestion(_("Another document with same name open!"),
148 MakeDisplayPath(fname, 50),
149 _("Replace with current document?")))
151 bufferlist.close(bufferlist.getBuffer(fname));
153 // Ok, change the name of the buffer, but don't save!
154 buffer->setFileName(fname);
157 ShowMessage(buffer, _("Document renamed to '"),
158 MakeDisplayPath(fname), _("', but not saved..."));
161 } // Check whether the file exists
163 FileInfo const myfile(fname);
164 if (myfile.isOK() && !Alert::askQuestion(_("Document already exists:"),
165 MakeDisplayPath(fname, 50),
170 // Ok, change the name of the buffer
171 buffer->setFileName(fname);
173 bool unnamed = buffer->isUnnamed();
174 buffer->setUnnamed(false);
176 if (!MenuWrite(bv, buffer)) {
177 buffer->setFileName(oldname);
178 buffer->setUnnamed(unnamed);
179 ShowMessage(buffer, _("Document could not be saved!"),
180 _("Holding the old name."), MakeDisplayPath(oldname));
183 // now remove the oldname autosave file if existant!
184 removeAutosaveFile(oldname);
189 int MenuRunChktex(Buffer * buffer)
193 if (buffer->isSGML()) {
194 Alert::alert(_("Chktex does not work with SGML derived documents."));
197 ret = buffer->runChktex();
203 s = _("No warnings found.");
204 } else if (ret == 1) {
205 s = _("One warning found.");
206 t = _("Use `Navigate->Error' to find it.");
209 s += _(" warnings found.");
210 t = _("Use `Navigate->Error' to find them.");
212 Alert::alert(_("Chktex run successfully"), s, t);
214 Alert::alert(_("Error!"), _("It seems chktex does not work."));
222 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
225 if (!bufferlist.qwriteAll())
228 lastfiles->writeFile(lyxrc.lastfiles);
231 // Set a flag that we do quitting from the program,
232 // so no refreshes are necessary.
235 // close buffers first
236 bufferlist.closeAll();
238 // do any other cleanup procedures now
239 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
241 DestroyLyXTmpDir(system_tempdir);
249 class AutoSaveBuffer : public ForkedProcess {
252 AutoSaveBuffer(BufferView & bv, string const & fname)
253 : bv_(bv), fname_(fname) {}
255 virtual ForkedProcess * clone() const {
256 return new AutoSaveBuffer(*this);
262 virtual int generateChild();
269 int AutoSaveBuffer::start()
271 command_ = _("Auto-saving $$f");
272 command_ = subst(command_, "$$f", fname_);
273 return runNonBlocking();
277 int AutoSaveBuffer::generateChild()
279 // tmp_ret will be located (usually) in /tmp
280 // will that be a problem?
281 pid_t const pid = fork(); // If you want to debug the autosave
282 // you should set pid to -1, and comment out the
284 if (pid == 0 || pid == -1) {
285 // pid = -1 signifies that lyx was unable
286 // to fork. But we will do the save
290 string const tmp_ret = lyx::tempName(string(), "lyxauto");
291 if (!tmp_ret.empty()) {
292 bv_.buffer()->writeFile(tmp_ret);
293 // assume successful write of tmp_ret
294 if (!lyx::rename(tmp_ret, fname_)) {
296 // most likely couldn't move between filesystems
297 // unless write of tmp_ret failed
298 // so remove tmp file (if it exists)
299 lyx::unlink(tmp_ret);
306 // failed to write/rename tmp_ret so try writing direct
307 if (!bv_.buffer()->writeFile(fname_)) {
308 // It is dangerous to do this in the child,
309 // but safe in the parent, so...
311 bv_.owner()->message(_("Autosave failed!"));
314 if (pid == 0) { // we are the child so...
324 void AutoSave(BufferView * bv)
325 // should probably be moved into BufferList (Lgb)
326 // Perfect target for a thread...
328 if (!bv->available())
331 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
332 // We don't save now, but we'll try again later
333 bv->owner()->resetAutosaveTimer();
337 bv->owner()->message(_("Autosaving current document..."));
339 // create autosave filename
340 string fname = bv->buffer()->filePath();
342 fname += OnlyFilename(bv->buffer()->fileName());
345 AutoSaveBuffer autosave(*bv, fname);
348 bv->buffer()->markBakClean();
349 bv->owner()->resetAutosaveTimer();
354 // Copyright CHT Software Service GmbH
357 // create new file with template
360 Buffer * NewFile(string const & filename)
362 // Split argument by :
364 string tmpname = split(filename, name, ':');
365 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
366 if (name.length() == 1
367 && isalpha(static_cast<unsigned char>(name[0]))
368 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
370 name += token(tmpname, ':', 0);
371 tmpname = split(tmpname, ':');
374 lyxerr[Debug::INFO] << "Arg is " << filename
375 << "\nName is " << name
376 << "\nTemplate is " << tmpname << endl;
378 // find a free buffer
379 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
381 lastfiles->newFile(tmpbuf->fileName());
386 // Insert ascii file (if filename is empty, prompt for one)
387 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
389 if (!bv->available())
392 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
399 // clear the selection
400 bool flag = (bv->text == bv->getLyXText());
402 bv->beforeChange(bv->text);
404 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
406 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
409 BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
413 // Insert ascii file (if filename is empty, prompt for one)
414 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
419 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
420 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
422 FileDialog::Result result = fileDlg.Select(bv->owner()->buffer()->filePath());
424 if (result.first == FileDialog::Later)
427 fname = result.second;
435 if (!fi.readable()) {
436 Alert::err_alert(_("Error! Specified file is unreadable: "),
437 MakeDisplayPath(fname, 50));
441 ifstream ifs(fname.c_str());
443 Alert::err_alert(_("Error! Cannot open specified file: "),
444 MakeDisplayPath(fname, 50));
448 ifs.unsetf(ios::skipws);
449 istream_iterator<char> ii(ifs);
450 istream_iterator<char> end;
451 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
452 // We use this until the compilers get better...
454 copy(ii, end, back_inserter(tmp));
455 string const tmpstr(tmp.begin(), tmp.end());
457 // This is what we want to use and what we will use once the
458 // compilers get good enough.
459 //string tmpstr(ii, end); // yet a reason for using std::string
460 // alternate approach to get the file into a string:
462 copy(ii, end, back_inserter(tmpstr));
469 void MenuInsertLabel(BufferView * bv, string const & arg)
472 bv->owner()->prohibitInput();
474 Paragraph * par = bv->getLyXText()->cursor.par();
475 LyXLayout_ptr layout = par->layout();
476 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
477 Paragraph * par2 = par->previous();
479 LyXLayout_ptr const & layout2 = par2->layout();
481 if (layout2->latextype != LATEX_PARAGRAPH) {
486 string text = layout->latexname().substr(0, 3);
487 if (layout->latexname() == "theorem")
488 text = "thm"; // Create a correct prefix for prettyref
491 if (layout->latextype == LATEX_PARAGRAPH ||
492 lyxrc.label_init_length < 0)
494 string par_text = par->asString(bv->buffer(), false);
495 for (int i = 0; i < lyxrc.label_init_length; ++i) {
496 if (par_text.empty())
499 par_text = split(par_text, head, ' ');
501 text += '-'; // Is it legal to use spaces in
506 pair<bool, string> result =
507 Alert::askForText(_("Enter new label to insert:"), text);
509 label = trim(result.second);
512 if (!label.empty()) {
513 InsetCommandParams p("label", label);
514 InsetLabel * inset = new InsetLabel(p);
515 bv->insertInset(inset);
517 bv->owner()->allowInput();
521 // This function runs "configure" and then rereads lyx.defaults to
522 // reconfigure the automatic settings.
523 void Reconfigure(BufferView * bv)
525 bv->owner()->message(_("Running configure..."));
527 // Run configure in user lyx directory
530 one.startscript(Systemcall::Wait,
531 AddName(system_lyxdir, "configure"));
533 bv->owner()->message(_("Reloading configuration..."));
534 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
535 Alert::alert(_("The system has been reconfigured."),
536 _("You need to restart LyX to make use of any"),
537 _("updated document class specifications."));