2 * \file frontend_helpers.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "frontend_helpers.h"
17 #include "BufferParams.h"
24 #include "frontends/FileDialog.h"
25 #include "frontends/alert.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h"
29 #include "support/Package.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxalgo.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Path.h"
36 #include "support/Systemcall.h"
38 #include <boost/cregex.hpp>
39 #include <boost/regex.hpp>
52 using support::ascii_lowercase;
53 using support::bformat;
54 using support::compare_ascii_no_case;
55 using support::contains;
56 using support::getVectorFromString;
58 using support::prefixIs;
69 vector<string> const init_possible_cite_commands()
71 char const * const pos[] = {
73 "citet", "citep", "citealt", "citealp",
74 "citeauthor", "citeyear", "citeyearpar",
75 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
76 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
77 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
79 "footcite", "footcitet", "footcitep", "footcitealt",
80 "footcitealp", "footciteauthor", "footciteyear",
86 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
88 return vector<string>(pos, pos + size_pos);
92 vector<string> const & possible_cite_commands()
94 static vector<string> const pos = init_possible_cite_commands();
99 bool is_possible_cite_command(string const & input)
101 vector<string> const & possibles = possible_cite_commands();
102 vector<string>::const_iterator const end = possibles.end();
103 return std::find(possibles.begin(), end, input) != end;
107 string const default_cite_command(CiteEngine engine)
114 case ENGINE_NATBIB_AUTHORYEAR:
117 case ENGINE_NATBIB_NUMERICAL:
128 static const docstring TheBibliographyRef(from_ascii("TheBibliographyRef"));
133 string const asValidLatexCommand(string const & input,
134 CiteEngine const engine)
136 string const default_str = default_cite_command(engine);
137 if (!is_possible_cite_command(input))
143 output = default_str;
146 case ENGINE_NATBIB_AUTHORYEAR:
147 case ENGINE_NATBIB_NUMERICAL:
148 if (input == "cite" || input == "citefield" ||
149 input == "citetitle" || input == "cite*")
150 output = default_str;
151 else if (prefixIs(input, "foot"))
152 output = input.substr(4);
157 case ENGINE_JURABIB: {
158 // Jurabib does not support the 'uppercase' natbib style.
160 output = string(1, 'c') + input.substr(1);
164 // Jurabib does not support the 'full' natbib style.
165 string::size_type const n = output.size() - 1;
166 if (output != "cite*" && output[n] == '*')
167 output = output.substr(0, n);
177 docstring const familyName(docstring const & name)
182 // Very simple parser
183 docstring fname = name;
185 // possible authorname combinations are:
186 // "Surname, FirstName"
188 // "FirstName Surname"
190 docstring::size_type idx = fname.find(',');
191 if (idx != docstring::npos)
192 return ltrim(fname.substr(0, idx));
193 idx = fname.rfind('.');
194 if (idx != docstring::npos)
195 fname = ltrim(fname.substr(idx + 1));
196 // test if we have a LaTeX Space in front
197 if (fname[0] == '\\')
198 return fname.substr(2);
204 docstring const getAbbreviatedAuthor(InfoMap const & map, string const & key)
206 BOOST_ASSERT(!map.empty());
208 InfoMap::const_iterator it = map.find(key);
211 docstring const & data = it->second;
213 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
214 docstring::size_type const pos = data.find(TheBibliographyRef);
215 if (pos != docstring::npos) {
220 docstring const opt = trim(data.substr(0, pos - 1));
225 split(opt, authors, '(');
229 docstring author = parseBibTeX(data, "author");
232 author = parseBibTeX(data, "editor");
234 if (author.empty()) {
235 author = parseBibTeX(data, "key");
238 return from_utf8(key);
242 vector<docstring> const authors = getVectorFromString(author, from_ascii(" and "));
246 if (authors.size() == 2)
247 return bformat(_("%1$s and %2$s"),
248 familyName(authors[0]), familyName(authors[1]));
250 if (authors.size() > 2)
251 return bformat(_("%1$s et al."), familyName(authors[0]));
253 return familyName(authors[0]);
257 docstring const getYear(InfoMap const & map, string const & key)
259 BOOST_ASSERT(!map.empty());
261 InfoMap::const_iterator it = map.find(key);
264 docstring const & data = it->second;
266 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
267 docstring::size_type const pos = data.find(TheBibliographyRef);
268 if (pos != docstring::npos) {
273 docstring const opt =
274 trim(data.substr(0, pos - 1));
279 docstring const tmp = split(opt, authors, '(');
281 split(tmp, year, ')');
286 docstring year = parseBibTeX(data, "year");
296 // A functor for use with std::sort, leading to case insensitive sorting
297 class compareNoCase: public std::binary_function<string, string, bool>
300 bool operator()(string const & s1, string const & s2) const {
301 return compare_ascii_no_case(s1, s2) < 0;
308 vector<string> const getKeys(InfoMap const & map)
310 vector<string> bibkeys;
311 InfoMap::const_iterator it = map.begin();
312 InfoMap::const_iterator end = map.end();
313 for (; it != end; ++it) {
314 bibkeys.push_back(it->first);
317 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
322 docstring const getInfo(InfoMap const & map, string const & key)
324 BOOST_ASSERT(!map.empty());
326 InfoMap::const_iterator it = map.find(key);
329 docstring const & data = it->second;
331 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
332 docstring::size_type const pos = data.find(TheBibliographyRef);
333 if (pos != docstring::npos) {
334 docstring::size_type const pos2 = pos + TheBibliographyRef.size();
335 docstring const info = trim(data.substr(pos2));
339 // Search for all possible "required" keys
340 docstring author = parseBibTeX(data, "author");
342 author = parseBibTeX(data, "editor");
344 docstring year = parseBibTeX(data, "year");
345 docstring title = parseBibTeX(data, "title");
346 docstring booktitle = parseBibTeX(data, "booktitle");
347 docstring chapter = parseBibTeX(data, "chapter");
348 docstring number = parseBibTeX(data, "number");
349 docstring volume = parseBibTeX(data, "volume");
350 docstring pages = parseBibTeX(data, "pages");
351 docstring annote = parseBibTeX(data, "annote");
352 docstring media = parseBibTeX(data, "journal");
354 media = parseBibTeX(data, "publisher");
356 media = parseBibTeX(data, "school");
358 media = parseBibTeX(data, "institution");
360 odocstringstream result;
362 result << author << ", ";
365 if (!booktitle.empty())
366 result << ", in " << booktitle;
367 if (!chapter.empty())
368 result << ", Ch. " << chapter;
370 result << ", " << media;
372 result << ", vol. " << volume;
374 result << ", no. " << number;
376 result << ", pp. " << pages;
378 result << ", " << year;
380 result << "\n\n" << annote;
382 docstring const result_str = rtrim(result.str());
383 if (!result_str.empty())
386 // This should never happen (or at least be very unusual!)
393 // Escape special chars.
394 // All characters are literals except: '.|*?+(){}[]^$\'
395 // These characters are literals when preceded by a "\", which is done here
396 // @todo: This function should be moved to support, and then the test in tests
397 // should be moved there as well.
398 string const escape_special_chars(string const & expr)
400 // Search for all chars '.|*?+(){}[^$]\'
401 // Note that '[' and '\' must be escaped.
402 // This is a limitation of boost::regex, but all other chars in BREs
403 // are assumed literal.
404 boost::regex reg("[].|*?+(){}^$\\[\\\\]");
406 // $& is a perl-like expression that expands to all
407 // of the current match
408 // The '$' must be prefixed with the escape character '\' for
409 // boost to treat it as a literal.
410 // Thus, to prefix a matched expression with '\', we use:
411 return boost::regex_replace(expr, reg, "\\\\$&");
415 // A functor for use with std::find_if, used to ascertain whether a
416 // data entry matches the required regex_
417 // @throws: boost::regex_error if the supplied regex pattern is not valid
418 // @todo: This function should be moved to support.
419 class RegexMatch : public std::unary_function<string, bool>
422 // re and icase are used to construct an instance of boost::RegEx.
423 // if icase is true, then matching is insensitive to case
424 RegexMatch(InfoMap const & m, string const & re, bool icase)
425 : map_(m), regex_(re, icase) {}
427 bool operator()(string const & key) const {
428 // the data searched is the key + its associated BibTeX/biblio
431 InfoMap::const_iterator info = map_.find(key);
432 if (info != map_.end())
434 data += ' ' + to_utf8(info->second);
436 // Attempts to find a match for the current RE
437 // somewhere in data.
438 return boost::regex_search(data, regex_);
442 mutable boost::regex regex_;
448 vector<string>::const_iterator
449 searchKeys(InfoMap const & theMap,
450 vector<string> const & keys,
451 string const & search_expr,
452 vector<string>::const_iterator start,
457 // Preliminary checks
458 if (start < keys.begin() || start >= keys.end())
461 string expr = trim(search_expr);
466 // We must escape special chars in the search_expr so that
467 // it is treated as a simple string by boost::regex.
468 expr = escape_special_chars(expr);
471 // Build the functor that will be passed to find_if.
472 RegexMatch const match(theMap, expr, !caseSensitive);
474 // Search the vector of 'keys' from 'start' for one
475 // that matches the predicate 'match'. Searching can
476 // be forward or backward from start.
478 return std::find_if(start, keys.end(), match);
480 vector<string>::const_reverse_iterator rit(start);
481 vector<string>::const_reverse_iterator rend = keys.rend();
482 rit = std::find_if(rit, rend, match);
486 // This is correct and always safe.
487 // (See Meyer's Effective STL, Item 28.)
488 return (++rit).base();
490 catch (boost::regex_error &) {
496 docstring const parseBibTeX(docstring data, string const & findkey)
498 // at first we delete all characters right of '%' and
499 // replace tabs through a space and remove leading spaces
500 // we read the data line by line so that the \n are
504 docstring dummy = token(data,'\n', Entries);
505 while (!dummy.empty()) {
507 dummy = subst(dummy, '\t', ' ');
509 dummy = ltrim(dummy);
510 // ignore lines with a beginning '%' or ignore all right of %
511 docstring::size_type const idx =
512 dummy.empty() ? docstring::npos : dummy.find('%');
513 if (idx != docstring::npos)
514 // Check if this is really a comment or just "\%"
515 if (idx == 0 || dummy[idx - 1] != '\\')
516 dummy.erase(idx, docstring::npos);
518 // This is "\%", so just erase the '\'
519 dummy.erase(idx - 1, 1);
520 // do we have a new token or a new line of
521 // the same one? In the first case we ignore
522 // the \n and in the second we replace it
524 if (!dummy.empty()) {
525 if (!contains(dummy, '='))
526 data_ += ' ' + dummy;
530 dummy = token(data, '\n', ++Entries);
533 // replace double commas with "" for easy scanning
534 data = subst(data_, from_ascii(",,"), from_ascii("\"\""));
540 // now get only the important line of the bibtex entry.
541 // all entries are devided by ',' except the last one.
543 // now we have same behaviour for all entries because the last one
547 // parsing of title and booktitle is different from the
548 // others, because booktitle contains title
550 dummy = token(data, ',', Entries++);
551 if (!dummy.empty()) {
552 found = contains(ascii_lowercase(dummy), from_ascii(findkey));
553 if (findkey == "title" &&
554 contains(ascii_lowercase(dummy), from_ascii("booktitle")))
557 } while (!found && !dummy.empty());
562 // we are not sure, if we get all, because "key= "blah, blah" is
564 // Therefore we read all until the next "=" character, which follows a
566 docstring keyvalue = dummy;
567 dummy = token(data, ',', Entries++);
568 while (!contains(dummy, '=') && !dummy.empty()) {
569 keyvalue += ',' + dummy;
570 dummy = token(data, ',', Entries++);
573 // replace double "" with originals ,, (two commas)
574 // leaving us with the all-important line
575 data = subst(keyvalue, from_ascii("\"\""), from_ascii(",,"));
580 // 2. if there is no opening '{' then a closing '{' is probably cruft.
581 if (!contains(data, '{'))
582 data = rtrim(data, "}");
583 // happens, when last keyword
584 docstring::size_type const idx =
585 !data.empty() ? data.find('=') : docstring::npos;
587 if (idx == docstring::npos)
590 data = trim(data.substr(idx));
593 if (data.length() < 2 || data[0] != '=')
596 // delete '=' and the following spaces
597 data = ltrim(data, " =");
598 if (data.length() < 2) {
599 // not long enough to find delimiters
602 docstring::size_type keypos = 1;
604 if (data[0] == '{') {
606 } else if (data[0] == '"') {
609 // no {} and no "", pure data but with a
610 // possible ',' at the end
611 return rtrim(data, ",");
613 docstring tmp = data.substr(keypos);
614 while (tmp.find('{') != docstring::npos &&
615 tmp.find('}') != docstring::npos &&
616 tmp.find('{') < tmp.find('}') &&
617 tmp.find('{') < tmp.find(enclosing)) {
619 keypos += tmp.find('{') + 1;
620 tmp = data.substr(keypos);
621 keypos += tmp.find('}') + 1;
622 tmp = data.substr(keypos);
624 if (tmp.find(enclosing) == docstring::npos)
627 keypos += tmp.find(enclosing);
628 return data.substr(1, keypos - 1);
638 char const * const citeCommands[] = {
639 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
640 "citeyear", "citeyearpar" };
642 unsigned int const nCiteCommands =
643 sizeof(citeCommands) / sizeof(char *);
645 CiteStyle const citeStyles[] = {
646 CITE, CITET, CITEP, CITEALT, CITEALP,
647 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
649 unsigned int const nCiteStyles =
650 sizeof(citeStyles) / sizeof(CiteStyle);
652 CiteStyle const citeStylesFull[] = {
653 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
655 unsigned int const nCiteStylesFull =
656 sizeof(citeStylesFull) / sizeof(CiteStyle);
658 CiteStyle const citeStylesUCase[] = {
659 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
661 unsigned int const nCiteStylesUCase =
662 sizeof(citeStylesUCase) / sizeof(CiteStyle);
667 CitationStyle::CitationStyle(string const & command)
668 : style(CITE), full(false), forceUCase(false)
673 string cmd = command;
679 string::size_type const n = cmd.size() - 1;
680 if (cmd != "cite" && cmd[n] == '*') {
682 cmd = cmd.substr(0,n);
685 char const * const * const last = citeCommands + nCiteCommands;
686 char const * const * const ptr = std::find(citeCommands, last, cmd);
689 size_t idx = ptr - citeCommands;
690 style = citeStyles[idx];
695 string const CitationStyle::asLatexStr() const
697 string cite = citeCommands[style];
699 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
700 if (std::find(citeStylesFull, last, style) != last)
705 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
706 if (std::find(citeStylesUCase, last, style) != last)
714 vector<CiteStyle> const getCiteStyles(CiteEngine const engine)
716 unsigned int nStyles = 0;
717 unsigned int start = 0;
724 case ENGINE_NATBIB_AUTHORYEAR:
725 case ENGINE_NATBIB_NUMERICAL:
726 nStyles = nCiteStyles - 1;
730 nStyles = nCiteStyles;
735 typedef vector<CiteStyle> cite_vec;
737 cite_vec styles(nStyles);
738 cite_vec::size_type i = 0;
740 for (; i != styles.size(); ++i, ++j)
741 styles[i] = citeStyles[j];
747 vector<docstring> const
748 getNumericalStrings(string const & key,
749 InfoMap const & map, vector<CiteStyle> const & styles)
752 return vector<docstring>();
754 docstring const author = getAbbreviatedAuthor(map, key);
755 docstring const year = getYear(map, key);
756 if (author.empty() || year.empty())
757 return vector<docstring>();
759 vector<docstring> vec(styles.size());
760 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
766 str = from_ascii("[#ID]");
770 str = author + " [#ID]";
774 str = author + " #ID";
778 str = from_ascii("#ID");
790 str = '(' + year + ')';
801 vector<docstring> const
802 getAuthorYearStrings(string const & key,
803 InfoMap const & map, vector<CiteStyle> const & styles)
806 return vector<docstring>();
808 docstring const author = getAbbreviatedAuthor(map, key);
809 docstring const year = getYear(map, key);
810 if (author.empty() || year.empty())
811 return vector<docstring>();
813 vector<docstring> vec(styles.size());
814 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
819 // jurabib only: Author/Annotator
820 // (i.e. the "before" field, 2nd opt arg)
821 str = author + "/<" + _("before") + '>';
825 str = author + " (" + year + ')';
829 str = '(' + author + ", " + year + ')';
833 str = author + ' ' + year ;
837 str = author + ", " + year ;
849 str = '(' + year + ')';
859 } // namespace biblio
863 vector<FamilyPair> const getFamilyData()
865 vector<FamilyPair> family(5);
869 pr.first = _("No change");
870 pr.second = Font::IGNORE_FAMILY;
873 pr.first = _("Roman");
874 pr.second = Font::ROMAN_FAMILY;
877 pr.first = _("Sans Serif");
878 pr.second = Font::SANS_FAMILY;
881 pr.first = _("Typewriter");
882 pr.second = Font::TYPEWRITER_FAMILY;
885 pr.first = _("Reset");
886 pr.second = Font::INHERIT_FAMILY;
893 vector<SeriesPair> const getSeriesData()
895 vector<SeriesPair> series(4);
899 pr.first = _("No change");
900 pr.second = Font::IGNORE_SERIES;
903 pr.first = _("Medium");
904 pr.second = Font::MEDIUM_SERIES;
907 pr.first = _("Bold");
908 pr.second = Font::BOLD_SERIES;
911 pr.first = _("Reset");
912 pr.second = Font::INHERIT_SERIES;
919 vector<ShapePair> const getShapeData()
921 vector<ShapePair> shape(6);
925 pr.first = _("No change");
926 pr.second = Font::IGNORE_SHAPE;
929 pr.first = _("Upright");
930 pr.second = Font::UP_SHAPE;
933 pr.first = _("Italic");
934 pr.second = Font::ITALIC_SHAPE;
937 pr.first = _("Slanted");
938 pr.second = Font::SLANTED_SHAPE;
941 pr.first = _("Small Caps");
942 pr.second = Font::SMALLCAPS_SHAPE;
945 pr.first = _("Reset");
946 pr.second = Font::INHERIT_SHAPE;
953 vector<SizePair> const getSizeData()
955 vector<SizePair> size(14);
959 pr.first = _("No change");
960 pr.second = Font::IGNORE_SIZE;
963 pr.first = _("Tiny");
964 pr.second = Font::SIZE_TINY;
967 pr.first = _("Smallest");
968 pr.second = Font::SIZE_SCRIPT;
971 pr.first = _("Smaller");
972 pr.second = Font::SIZE_FOOTNOTE;
975 pr.first = _("Small");
976 pr.second = Font::SIZE_SMALL;
979 pr.first = _("Normal");
980 pr.second = Font::SIZE_NORMAL;
983 pr.first = _("Large");
984 pr.second = Font::SIZE_LARGE;
987 pr.first = _("Larger");
988 pr.second = Font::SIZE_LARGER;
991 pr.first = _("Largest");
992 pr.second = Font::SIZE_LARGEST;
995 pr.first = _("Huge");
996 pr.second = Font::SIZE_HUGE;
999 pr.first = _("Huger");
1000 pr.second = Font::SIZE_HUGER;
1003 pr.first = _("Increase");
1004 pr.second = Font::INCREASE_SIZE;
1007 pr.first = _("Decrease");
1008 pr.second = Font::DECREASE_SIZE;
1011 pr.first = _("Reset");
1012 pr.second = Font::INHERIT_SIZE;
1019 vector<BarPair> const getBarData()
1021 vector<BarPair> bar(5);
1025 pr.first = _("No change");
1029 pr.first = _("Emph");
1030 pr.second = EMPH_TOGGLE;
1033 pr.first = _("Underbar");
1034 pr.second = UNDERBAR_TOGGLE;
1037 pr.first = _("Noun");
1038 pr.second = NOUN_TOGGLE;
1041 pr.first = _("Reset");
1042 pr.second = INHERIT;
1049 vector<ColorPair> const getColorData()
1051 vector<ColorPair> color(11);
1055 pr.first = _("No change");
1056 pr.second = Color::ignore;
1059 pr.first = _("No color");
1060 pr.second = Color::none;
1063 pr.first = _("Black");
1064 pr.second = Color::black;
1067 pr.first = _("White");
1068 pr.second = Color::white;
1071 pr.first = _("Red");
1072 pr.second = Color::red;
1075 pr.first = _("Green");
1076 pr.second = Color::green;
1079 pr.first = _("Blue");
1080 pr.second = Color::blue;
1083 pr.first = _("Cyan");
1084 pr.second = Color::cyan;
1087 pr.first = _("Magenta");
1088 pr.second = Color::magenta;
1091 pr.first = _("Yellow");
1092 pr.second = Color::yellow;
1095 pr.first = _("Reset");
1096 pr.second = Color::inherit;
1107 : public std::binary_function<LanguagePair,
1111 Sorter() : loc_("") {};
1112 bool operator()(LanguagePair const & lhs,
1113 LanguagePair const & rhs) const {
1114 return loc_(lhs.first, rhs.first);
1123 vector<LanguagePair> const getLanguageData(bool character_dlg)
1125 vector<LanguagePair>::size_type const size = character_dlg ?
1126 languages.size() + 2 : languages.size();
1128 vector<LanguagePair> langs(size);
1130 if (character_dlg) {
1131 langs[0].first = _("No change");
1132 langs[0].second = "ignore";
1133 langs[1].first = _("Reset");
1134 langs[1].second = "reset";
1137 vector<string>::size_type i = character_dlg ? 2 : 0;
1138 for (Languages::const_iterator cit = languages.begin();
1139 cit != languages.end(); ++cit) {
1140 langs[i].first = _(cit->second.display());
1141 langs[i].second = cit->second.lang();
1145 // Don't sort "ignore" and "reset"
1146 vector<LanguagePair>::iterator begin = character_dlg ?
1147 langs.begin() + 2 : langs.begin();
1149 std::sort(begin, langs.end(), Sorter());
1154 } // namespace frontend
1156 using support::addName;
1157 using support::FileFilterList;
1158 using support::getExtension;
1159 using support::libFileSearch;
1160 using support::makeAbsPath;
1161 using support::makeRelPath;
1162 using support::onlyFilename;
1163 using support::onlyPath;
1164 using support::package;
1165 using support::prefixIs;
1166 using support::removeExtension;
1168 namespace frontend {
1171 docstring const browseFile(docstring const & filename,
1172 docstring const & title,
1173 FileFilterList const & filters,
1175 pair<docstring,docstring> const & dir1,
1176 pair<docstring,docstring> const & dir2)
1178 docstring lastPath = from_ascii(".");
1179 if (!filename.empty())
1180 lastPath = from_utf8(onlyPath(to_utf8(filename)));
1182 FileDialog fileDlg(title, LFUN_SELECT_FILE_SYNC, dir1, dir2);
1184 FileDialog::Result result;
1187 result = fileDlg.save(lastPath, filters,
1188 from_utf8(onlyFilename(to_utf8(filename))));
1190 result = fileDlg.open(lastPath, filters,
1191 from_utf8(onlyFilename(to_utf8(filename))));
1193 return result.second;
1197 docstring const browseRelFile(docstring const & filename,
1198 docstring const & refpath,
1199 docstring const & title,
1200 FileFilterList const & filters,
1202 pair<docstring,docstring> const & dir1,
1203 pair<docstring,docstring> const & dir2)
1205 docstring const fname = from_utf8(makeAbsPath(
1206 to_utf8(filename), to_utf8(refpath)).absFilename());
1208 docstring const outname = browseFile(fname, title, filters, save,
1210 docstring const reloutname = makeRelPath(outname, refpath);
1211 if (prefixIs(reloutname, from_ascii("../")))
1219 docstring const browseLibFile(docstring const & dir,
1220 docstring const & name,
1221 docstring const & ext,
1222 docstring const & title,
1223 FileFilterList const & filters)
1226 pair<docstring, docstring> const dir1(_("System files|#S#s"),
1227 from_utf8(addName(package().system_support().absFilename(), to_utf8(dir))));
1229 pair<docstring, docstring> const dir2(_("User files|#U#u"),
1230 from_utf8(addName(package().user_support().absFilename(), to_utf8(dir))));
1232 docstring const result = browseFile(from_utf8(
1233 libFileSearch(to_utf8(dir), to_utf8(name), to_utf8(ext)).absFilename()),
1234 title, filters, false, dir1, dir2);
1236 // remove the extension if it is the default one
1237 docstring noextresult;
1238 if (from_utf8(getExtension(to_utf8(result))) == ext)
1239 noextresult = from_utf8(removeExtension(to_utf8(result)));
1241 noextresult = result;
1243 // remove the directory, if it is the default one
1244 docstring const file = from_utf8(onlyFilename(to_utf8(noextresult)));
1245 if (from_utf8(libFileSearch(to_utf8(dir), to_utf8(file), to_utf8(ext)).absFilename()) == result)
1252 docstring const browseDir(docstring const & pathname,
1253 docstring const & title,
1254 pair<docstring,docstring> const & dir1,
1255 pair<docstring,docstring> const & dir2)
1257 docstring lastPath = from_ascii(".");
1258 if (!pathname.empty())
1259 lastPath = from_utf8(onlyPath(to_utf8(pathname)));
1261 FileDialog fileDlg(title, LFUN_SELECT_FILE_SYNC, dir1, dir2);
1263 FileDialog::Result const result =
1264 fileDlg.opendir(lastPath, from_utf8(onlyFilename(to_utf8(pathname))));
1266 return result.second;
1270 vector<docstring> const getLatexUnits()
1272 vector<docstring> units;
1274 char const * str = stringFromUnit(i);
1275 for (; str != 0; ++i, str = stringFromUnit(i))
1276 units.push_back(from_ascii(str));
1281 } // namespace frontend
1284 using support::bformat;
1285 using support::contains;
1286 using support::FileName;
1287 using support::getExtension;
1288 using support::getFileContents;
1289 using support::getVectorFromString;
1290 using support::libFileSearch;
1291 using support::onlyFilename;
1292 using support::package;
1293 using support::quoteName;
1294 using support::split;
1295 using support::Systemcall;
1296 using support::token;
1298 namespace frontend {
1300 void rescanTexStyles()
1302 // Run rescan in user lyx directory
1303 support::Path p(package().user_support());
1304 FileName const command = libFileSearch("scripts", "TeXFiles.py");
1306 int const status = one.startscript(Systemcall::Wait,
1307 lyx::support::os::python() + ' ' +
1308 quoteName(command.toFilesystemEncoding()));
1312 Alert::error(_("Could not update TeX information"),
1313 bformat(_("The script `%s' failed."), lyx::from_utf8(command.absFilename())));
1319 // Run texhash in user lyx directory
1320 support::Path p(package().user_support());
1322 //path to texhash through system
1324 one.startscript(Systemcall::Wait,"texhash");
1328 void getTexFileList(string const & filename, std::vector<string> & list)
1331 FileName const file = libFileSearch("", filename);
1335 list = getVectorFromString(getFileContents(file), "\n");
1337 // Normalise paths like /foo//bar ==> /foo/bar
1338 boost::RegEx regex("/{2,}");
1339 std::vector<string>::iterator it = list.begin();
1340 std::vector<string>::iterator end = list.end();
1341 for (; it != end; ++it) {
1342 *it = regex.Merge((*it), "/");
1345 // remove empty items and duplicates
1346 list.erase(std::remove(list.begin(), list.end(), ""), list.end());
1347 eliminate_duplicates(list);
1351 string const getListOfOptions(string const & classname, string const & type)
1353 FileName const filename(getTexFileFromList(classname, type));
1354 if (filename.empty())
1356 string optionList = string();
1357 std::ifstream is(filename.toFilesystemEncoding().c_str());
1361 if (contains(s,"DeclareOption")) {
1362 s = s.substr(s.find("DeclareOption"));
1363 s = split(s,'{'); // cut front
1364 s = token(s,'}',0); // cut end
1365 optionList += (s + '\n');
1372 string const getTexFileFromList(string const & file,
1373 string const & type)
1375 string file_ = file;
1376 // do we need to add the suffix?
1377 if (!(getExtension(file) == type))
1378 file_ += '.' + type;
1380 lyxerr << "Searching for file " << file_ << endl;
1384 lstfile = "clsFiles.lst";
1385 else if (type == "sty")
1386 lstfile = "styFiles.lst";
1387 else if (type == "bst")
1388 lstfile = "bstFiles.lst";
1389 else if (type == "bib")
1390 lstfile = "bibFiles.lst";
1391 FileName const abslstfile = libFileSearch(string(), lstfile);
1392 if (abslstfile.empty()) {
1393 lyxerr << "File `'" << lstfile << "' not found." << endl;
1396 string const allClasses = getFileContents(abslstfile);
1398 string classfile = token(allClasses, '\n', entries);
1400 while ((!contains(classfile, file) ||
1401 (onlyFilename(classfile) != file)) &&
1403 classfile = token(allClasses, '\n', ++entries);
1406 // now we have filename with full path
1407 lyxerr << "with full path: " << classfile << endl;
1412 } // namespace frontend