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"
24 #include "BufferView.h"
25 #include "lyxtextclasslist.h"
27 #include "insets/insetlabel.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
31 #include "frontends/GUIRunTime.h"
33 #include "support/FileInfo.h"
34 #include "support/filetools.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
57 extern bool finished; // all cleanup done just let it run through now.
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)
85 XFlush(GUIRunTime::x11Display());
87 if (!buffer->save()) {
88 if (Alert::askQuestion(_("Save failed. Rename and try again?"),
89 MakeDisplayPath(buffer->fileName(), 50),
90 _("(If not, document is not saved.)"))) {
91 return WriteAs(bv, buffer);
95 lastfiles->newFile(buffer->fileName());
101 // should be moved to BufferView.C
102 // Half of this func should be in LyXView, the rest in BufferView.
103 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
105 string fname = buffer->fileName();
106 string const oldname = fname;
108 if (filename.empty()) {
110 FileDialog fileDlg(bv->owner(),
111 _("Choose a filename to save document as"),
113 make_pair(string(_("Documents|#o#O")),
114 string(lyxrc.document_path)),
115 make_pair(string(_("Templates|#T#t")),
116 string(lyxrc.template_path)));
118 if (!IsLyXFilename(fname))
121 FileDialog::Result result =
122 fileDlg.Select(OnlyPath(fname),
123 _("*.lyx|LyX Documents (*.lyx)"),
124 OnlyFilename(fname));
126 if (result.first == FileDialog::Later)
129 fname = result.second;
134 // Make sure the absolute filename ends with appropriate suffix
135 fname = MakeAbsPath(fname);
136 if (!IsLyXFilename(fname))
141 // Same name as we have already?
142 if (!buffer->isUnnamed() && fname == oldname) {
143 if (!Alert::askQuestion(_("Same name as document already has:"),
144 MakeDisplayPath(fname, 50),
147 // Falls through to name change and save
149 // No, but do we have another file with this name open?
150 else if (!buffer->isUnnamed() && bufferlist.exists(fname)) {
151 if (Alert::askQuestion(_("Another document with same name open!"),
152 MakeDisplayPath(fname, 50),
153 _("Replace with current document?")))
155 bufferlist.close(bufferlist.getBuffer(fname));
157 // Ok, change the name of the buffer, but don't save!
158 buffer->setFileName(fname);
161 ShowMessage(buffer, _("Document renamed to '"),
162 MakeDisplayPath(fname), _("', but not saved..."));
165 } // Check whether the file exists
167 FileInfo const myfile(fname);
168 if (myfile.isOK() && !Alert::askQuestion(_("Document already exists:"),
169 MakeDisplayPath(fname, 50),
174 // Ok, change the name of the buffer
175 buffer->setFileName(fname);
177 bool unnamed = buffer->isUnnamed();
178 buffer->setUnnamed(false);
180 if (!MenuWrite(bv, buffer)) {
181 buffer->setFileName(oldname);
182 buffer->setUnnamed(unnamed);
183 ShowMessage(buffer, _("Document could not be saved!"),
184 _("Holding the old name."), MakeDisplayPath(oldname));
187 // now remove the oldname autosave file if existant!
188 removeAutosaveFile(oldname);
193 int MenuRunChktex(Buffer * buffer)
197 if (buffer->isSGML()) {
198 Alert::alert(_("Chktex does not work with SGML derived documents."));
201 ret = buffer->runChktex();
207 s = _("No warnings found.");
208 } else if (ret == 1) {
209 s = _("One warning found.");
210 t = _("Use `Navigate->Error' to find it.");
213 s += _(" warnings found.");
214 t = _("Use `Navigate->Error' to find them.");
216 Alert::alert(_("Chktex run successfully"), s, t);
218 Alert::alert(_("Error!"), _("It seems chktex does not work."));
226 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
229 if (!bufferlist.qwriteAll())
232 lastfiles->writeFile(lyxrc.lastfiles);
235 // Set a flag that we do quitting from the program,
236 // so no refreshes are necessary.
239 // close buffers first
240 bufferlist.closeAll();
242 // do any other cleanup procedures now
243 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
245 DestroyLyXTmpDir(system_tempdir);
252 void AutoSave(BufferView * bv)
253 // should probably be moved into BufferList (Lgb)
254 // Perfect target for a thread...
256 if (!bv->available())
259 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
260 // We don't save now, but we'll try again later
261 bv->owner()->resetAutosaveTimer();
265 bv->owner()->message(_("Autosaving current document..."));
267 // create autosave filename
268 string fname = bv->buffer()->filePath();
270 fname += OnlyFilename(bv->buffer()->fileName());
273 // tmp_ret will be located (usually) in /tmp
274 // will that be a problem?
275 pid_t const pid = fork(); // If you want to debug the autosave
276 // you should set pid to -1, and comment out the
278 if (pid == 0 || pid == -1) {
279 // pid = -1 signifies that lyx was unable
280 // to fork. But we will do the save
284 string const tmp_ret = lyx::tempName(string(), "lyxauto");
285 if (!tmp_ret.empty()) {
286 bv->buffer()->writeFile(tmp_ret, 1);
287 // assume successful write of tmp_ret
288 if (!lyx::rename(tmp_ret, fname)) {
290 // most likely couldn't move between filesystems
291 // unless write of tmp_ret failed
292 // so remove tmp file (if it exists)
293 lyx::unlink(tmp_ret);
300 // failed to write/rename tmp_ret so try writing direct
301 if (!bv->buffer()->writeFile(fname, 1)) {
302 // It is dangerous to do this in the child,
303 // but safe in the parent, so...
305 bv->owner()->message(_("Autosave failed!"));
308 if (pid == 0) { // we are the child so...
313 bv->buffer()->markBakClean();
314 bv->owner()->resetAutosaveTimer();
319 // Copyright CHT Software Service GmbH
322 // create new file with template
325 Buffer * NewLyxFile(string const & filename)
327 // Split argument by :
329 string tmpname = split(filename, name, ':');
330 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
331 if (name.length() == 1
332 && isalpha(static_cast<unsigned char>(name[0]))
333 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
335 name += token(tmpname, ':', 0);
336 tmpname = split(tmpname, ':');
339 lyxerr[Debug::INFO] << "Arg is " << filename
340 << "\nName is " << name
341 << "\nTemplate is " << tmpname << endl;
343 // find a free buffer
344 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
346 lastfiles->newFile(tmpbuf->fileName());
351 // Insert ascii file (if filename is empty, prompt for one)
352 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
354 if (!bv->available())
357 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
364 // clear the selection
365 bool flag = (bv->text == bv->getLyXText());
367 bv->beforeChange(bv->text);
369 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
371 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
374 BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
378 // Insert ascii file (if filename is empty, prompt for one)
379 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
384 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
385 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
387 FileDialog::Result result = fileDlg.Select(bv->owner()->buffer()->filePath());
389 if (result.first == FileDialog::Later)
392 fname = result.second;
400 if (!fi.readable()) {
401 Alert::err_alert(_("Error! Specified file is unreadable: "),
402 MakeDisplayPath(fname, 50));
406 ifstream ifs(fname.c_str());
408 Alert::err_alert(_("Error! Cannot open specified file: "),
409 MakeDisplayPath(fname, 50));
413 ifs.unsetf(ios::skipws);
414 istream_iterator<char> ii(ifs);
415 istream_iterator<char> end;
416 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
417 // We use this until the compilers get better...
419 copy(ii, end, back_inserter(tmp));
420 string const tmpstr(tmp.begin(), tmp.end());
422 // This is what we want to use and what we will use once the
423 // compilers get good enough.
424 //string tmpstr(ii, end); // yet a reason for using std::string
425 // alternate approach to get the file into a string:
427 copy(ii, end, back_inserter(tmpstr));
434 void MenuInsertLabel(BufferView * bv, string const & arg)
437 bv->owner()->prohibitInput();
439 Paragraph * par = bv->getLyXText()->cursor.par();
440 LyXTextClass const & tclass =
441 textclasslist[bv->buffer()->params.textclass];
442 LyXLayout const * layout = &tclass[par->layout()];
444 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
445 Paragraph * par2 = par->previous();
446 LyXLayout const * layout2 = &tclass[par2->layout()];
447 if (layout2->latextype != LATEX_PARAGRAPH) {
452 string text = layout->latexname().substr(0, 3);
453 if (layout->latexname() == "theorem")
454 text = "thm"; // Create a correct prefix for prettyref
457 if (layout->latextype == LATEX_PARAGRAPH ||
458 lyxrc.label_init_length < 0)
460 string par_text = par->asString(bv->buffer(), false);
461 for (int i = 0; i < lyxrc.label_init_length; ++i) {
462 if (par_text.empty())
465 par_text = split(par_text, head, ' ');
467 text += '-'; // Is it legal to use spaces in
472 pair<bool, string> result =
473 Alert::askForText(_("Enter new label to insert:"), text);
475 label = frontStrip(strip(result.second));
478 if (!label.empty()) {
479 InsetCommandParams p("label", label);
480 InsetLabel * inset = new InsetLabel(p);
481 bv->insertInset(inset);
483 bv->owner()->allowInput();
487 // This function runs "configure" and then rereads lyx.defaults to
488 // reconfigure the automatic settings.
489 void Reconfigure(BufferView * bv)
491 bv->owner()->message(_("Running configure..."));
493 // Run configure in user lyx directory
496 one.startscript(Systemcall::Wait,
497 AddName(system_lyxdir, "configure"));
499 bv->owner()->message(_("Reloading configuration..."));
500 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
501 Alert::alert(_("The system has been reconfigured."),
502 _("You need to restart LyX to make use of any"),
503 _("updated document class specifications."));