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"
20 #include "frontends/LyXView.h"
24 #include "BufferView.h"
25 #include "lyxtextclasslist.h"
27 #include "insets/insetlabel.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.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)
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.Select(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);
249 void AutoSave(BufferView * bv)
250 // should probably be moved into BufferList (Lgb)
251 // Perfect target for a thread...
253 if (!bv->available())
256 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
257 // We don't save now, but we'll try again later
258 bv->owner()->resetAutosaveTimer();
262 bv->owner()->message(_("Autosaving current document..."));
264 // create autosave filename
265 string fname = bv->buffer()->filePath();
267 fname += OnlyFilename(bv->buffer()->fileName());
270 // tmp_ret will be located (usually) in /tmp
271 // will that be a problem?
272 pid_t const pid = fork(); // If you want to debug the autosave
273 // you should set pid to -1, and comment out the
275 if (pid == 0 || pid == -1) {
276 // pid = -1 signifies that lyx was unable
277 // to fork. But we will do the save
281 string const tmp_ret = lyx::tempName(string(), "lyxauto");
282 if (!tmp_ret.empty()) {
283 bv->buffer()->writeFile(tmp_ret, 1);
284 // assume successful write of tmp_ret
285 if (!lyx::rename(tmp_ret, fname)) {
287 // most likely couldn't move between filesystems
288 // unless write of tmp_ret failed
289 // so remove tmp file (if it exists)
290 lyx::unlink(tmp_ret);
297 // failed to write/rename tmp_ret so try writing direct
298 if (!bv->buffer()->writeFile(fname, 1)) {
299 // It is dangerous to do this in the child,
300 // but safe in the parent, so...
302 bv->owner()->message(_("Autosave failed!"));
305 if (pid == 0) { // we are the child so...
310 bv->buffer()->markBakClean();
311 bv->owner()->resetAutosaveTimer();
316 // Copyright CHT Software Service GmbH
319 // create new file with template
322 Buffer * NewLyxFile(string const & filename)
324 // Split argument by :
326 string tmpname = split(filename, name, ':');
327 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
328 if (name.length() == 1
329 && isalpha(static_cast<unsigned char>(name[0]))
330 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
332 name += token(tmpname, ':', 0);
333 tmpname = split(tmpname, ':');
336 lyxerr[Debug::INFO] << "Arg is " << filename
337 << "\nName is " << name
338 << "\nTemplate is " << tmpname << endl;
340 // find a free buffer
341 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
343 lastfiles->newFile(tmpbuf->fileName());
348 // Insert ascii file (if filename is empty, prompt for one)
349 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
351 if (!bv->available())
354 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
361 // clear the selection
362 bool flag = (bv->text == bv->getLyXText());
364 bv->beforeChange(bv->text);
366 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
368 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
371 BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
375 // Insert ascii file (if filename is empty, prompt for one)
376 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
381 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
382 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
384 FileDialog::Result result = fileDlg.Select(bv->owner()->buffer()->filePath());
386 if (result.first == FileDialog::Later)
389 fname = result.second;
397 if (!fi.readable()) {
398 Alert::err_alert(_("Error! Specified file is unreadable: "),
399 MakeDisplayPath(fname, 50));
403 ifstream ifs(fname.c_str());
405 Alert::err_alert(_("Error! Cannot open specified file: "),
406 MakeDisplayPath(fname, 50));
410 ifs.unsetf(ios::skipws);
411 istream_iterator<char> ii(ifs);
412 istream_iterator<char> end;
413 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
414 // We use this until the compilers get better...
416 copy(ii, end, back_inserter(tmp));
417 string const tmpstr(tmp.begin(), tmp.end());
419 // This is what we want to use and what we will use once the
420 // compilers get good enough.
421 //string tmpstr(ii, end); // yet a reason for using std::string
422 // alternate approach to get the file into a string:
424 copy(ii, end, back_inserter(tmpstr));
431 void MenuInsertLabel(BufferView * bv, string const & arg)
434 bv->owner()->prohibitInput();
436 Paragraph * par = bv->getLyXText()->cursor.par();
437 LyXTextClass const & tclass =
438 textclasslist[bv->buffer()->params.textclass];
439 LyXLayout const * layout = &tclass[par->layout()];
441 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
442 Paragraph * par2 = par->previous();
443 LyXLayout const * layout2 = &tclass[par2->layout()];
444 if (layout2->latextype != LATEX_PARAGRAPH) {
449 string text = layout->latexname().substr(0, 3);
450 if (layout->latexname() == "theorem")
451 text = "thm"; // Create a correct prefix for prettyref
454 if (layout->latextype == LATEX_PARAGRAPH ||
455 lyxrc.label_init_length < 0)
457 string par_text = par->asString(bv->buffer(), false);
458 for (int i = 0; i < lyxrc.label_init_length; ++i) {
459 if (par_text.empty())
462 par_text = split(par_text, head, ' ');
464 text += '-'; // Is it legal to use spaces in
469 pair<bool, string> result =
470 Alert::askForText(_("Enter new label to insert:"), text);
472 label = frontStrip(strip(result.second));
475 if (!label.empty()) {
476 InsetCommandParams p("label", label);
477 InsetLabel * inset = new InsetLabel(p);
478 bv->insertInset(inset);
480 bv->owner()->allowInput();
484 // This function runs "configure" and then rereads lyx.defaults to
485 // reconfigure the automatic settings.
486 void Reconfigure(BufferView * bv)
488 bv->owner()->message(_("Running configure..."));
490 // Run configure in user lyx directory
493 one.startscript(Systemcall::Wait,
494 AddName(system_lyxdir, "configure"));
496 bv->owner()->message(_("Reloading configuration..."));
497 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
498 Alert::alert(_("The system has been reconfigured."),
499 _("You need to restart LyX to make use of any"),
500 _("updated document class specifications."));