int main (int argc, char** argv) { UnitTest t (8); std::vector <std::string> options; options.push_back ("abc"); options.push_back ("abcd"); options.push_back ("abcde"); options.push_back ("bcdef"); options.push_back ("cdefg"); std::vector <std::string> matches; int result = autoComplete ("", options, matches); t.is (result, 0, "no match on empty string"); result = autoComplete ("x", options, matches); t.is (result, 0, "no match on wrong string"); result = autoComplete ("abcd", options, matches); t.is (result, 1, "exact match on 'abcd'"); t.is (matches[0], "abcd", "exact match on 'abcd'"); result = autoComplete ("ab", options, matches); t.is (result, 3, "partial match on 'ab'"); t.is (matches[0], "abc", "partial match on 'abc'"); t.is (matches[1], "abcd", "partial match on 'abcd'"); t.is (matches[2], "abcde", "partial match on 'abcde'"); return 0; }
void guess ( const std::string& type, std::vector<std::string>& options, std::string& candidate) { std::vector <std::string> matches; autoComplete (candidate, options, matches, context.config.getInteger ("abbreviation.minimum")); if (1 == matches.size ()) candidate = matches[0]; else if (0 == matches.size ()) candidate = ""; else { std::sort (matches.begin (), matches.end ()); std::string error = format (STRING_TEXT_AMBIGUOUS, type, candidate); for (size_t i = 0; i < matches.size (); ++i) { if (i) error += ", "; error += matches[i]; } throw error; } }
//////////////////////////////////////////////////////////////////////////////// // 0 = no // 1 = yes // 2 = all int confirm3 (const std::string& question) { std::vector <std::string> options; options.push_back ("Yes"); options.push_back ("yes"); options.push_back ("no"); options.push_back ("All"); options.push_back ("all"); std::string answer; std::vector <std::string> matches; do { std::cout << question << " (" << options[1] << "/" << options[2] << "/" << options[4] << ") "; std::getline (std::cin, answer); answer = trim (answer); autoComplete (answer, options, matches); } while (matches.size () != 1); if (matches[0] == "Yes") return 1; else if (matches[0] == "yes") return 1; else if (matches[0] == "All") return 2; else if (matches[0] == "all") return 2; else return 0; }
//////////////////////////////////////////////////////////////////////////////// // 0 = no // 1 = yes // 2 = all int confirm3 (const std::string& question) { std::vector <std::string> options; options.push_back (STRING_UTIL_CONFIRM_YES_U); options.push_back (STRING_UTIL_CONFIRM_YES); options.push_back (STRING_UTIL_CONFIRM_NO); options.push_back (STRING_UTIL_CONFIRM_ALL_U); options.push_back (STRING_UTIL_CONFIRM_ALL); std::string answer; std::vector <std::string> matches; do { std::cout << question << " (" << options[1] << "/" << options[2] << "/" << options[4] << ") "; std::getline (std::cin, answer); answer = trim (answer); autoComplete (answer, options, matches, 1); // Hard-coded 1. } while (matches.size () != 1); if (matches[0] == STRING_UTIL_CONFIRM_YES_U) return 1; else if (matches[0] == STRING_UTIL_CONFIRM_YES) return 1; else if (matches[0] == STRING_UTIL_CONFIRM_ALL_U) return 2; else if (matches[0] == STRING_UTIL_CONFIRM_ALL) return 2; else return 0; }
bool Duration::valid (const std::string& input) { std::string lower_input = lowerCase (input); // Assume the ordinal is 1, but look for an integer, just in case. double value = 1; Nibbler n (lower_input); n.getNumber (value); if (value < 0.0) value = -value; std::string units; n.getUntilEOS (units); // Non-trivial value with no units means the duration is specified in // seconds, and therefore a time_t. Consider it valid. if (value != 0.0 && units == "") return true; // Auto complete against all supported durations. std::vector <std::string> supported; for (unsigned int i = 0; i < NUM_DURATIONS; ++i) supported.push_back (durations[i]); std::vector <std::string> matches; if (autoComplete (units, supported, matches, context.config.getInteger ("abbreviation.minimum")) == 1) return true; return false; }
bool ClientConsole::onKeyPress (int32_t key, int16_t modifier) { switch (key) { case SDLK_TAB: if (modifier & KMOD_SHIFT) { toggleConsole(); return true; } } if (!_active) return false; switch (key) { case SDLK_ESCAPE: toggleConsole(); break; case SDLK_RETURN: executeCommandLine(); break; case SDLK_BACKSPACE: cursorDelete(); break; case SDLK_DELETE: cursorDelete(false); break; case SDLK_INSERT: _overwrite ^= true; break; case SDLK_LEFT: cursorLeft(); break; case SDLK_RIGHT: cursorRight(); break; case SDLK_UP: cursorUp(); break; case SDLK_DOWN: cursorDown(); break; case SDLK_TAB: autoComplete(); break; default: return false; } return true; }
void initializeColorRules () { // If color is not enable/supported, short circuit. if (! context.color ()) return; try { gsColor.clear (); gsPrecedence.clear (); // Load all the configuration values, filter to only the ones that begin with // "color.", then store name/value in gsColor, and name in rules. std::vector <std::string> rules; for (auto& v : context.config) { if (v.first.substr (0, 6) == "color.") { Color c (v.second); gsColor[v.first] = c; rules.push_back (v.first); } } // Load the rule.precedence.color list, split it, then autocomplete against // the 'rules' vector loaded above. std::vector <std::string> results; std::vector <std::string> precedence; split (precedence, context.config.get ("rule.precedence.color"), ','); for (auto& p : precedence) { // Add the leading "color." string. std::string rule = "color." + p; autoComplete (rule, rules, results, 3); // Hard-coded 3. for (auto& r : results) gsPrecedence.push_back (r); } } catch (const std::string& e) { context.error (e); } }
void initializeColorRules () { gsColor.clear (); gsPrecedence.clear (); // Load all the configuration values, filter to only the ones that begin with // "color.", then store name/value in gsColor, and name in rules. std::vector <std::string> rules; std::vector <std::string> variables; context.config.all (variables); std::vector <std::string>::iterator v; for (v = variables.begin (); v != variables.end (); ++v) { if (v->substr (0, 6) == "color.") { Color c (context.config.get (*v)); gsColor[*v] = c; rules.push_back (*v); } } // Load the rule.precedence.color list, split it, then autocomplete against // the 'rules' vector loaded above. std::vector <std::string> results; std::vector <std::string> precedence; split (precedence, context.config.get ("rule.precedence.color"), ','); std::vector <std::string>::iterator p; for (p = precedence.begin (); p != precedence.end (); ++p) { // Add the leading "color." string. std::string rule = "color." + *p; autoComplete (rule, rules, results, 3); // Hard-coded 3. std::vector <std::string>::iterator r; for (r = results.begin (); r != results.end (); ++r) gsPrecedence.push_back (*r); } }
//////////////////////////////////////////////////////////////////////////////// // Uses std::getline, because std::cin eats leading whitespace, and that means // that if a newline is entered, std::cin eats it and never returns from the // "std::cin >> answer;" line, but it does display the newline. This way, with // std::getline, the newline can be detected, and the prompt re-written. bool confirm (const std::string& question) { std::vector <std::string> options; options.push_back (STRING_UTIL_CONFIRM_YES); options.push_back (STRING_UTIL_CONFIRM_NO); std::string answer; std::vector <std::string> matches; do { std::cout << question << STRING_UTIL_CONFIRM_YN; std::getline (std::cin, answer); answer = std::cin.eof() ? STRING_UTIL_CONFIRM_NO : lowerCase (trim (answer)); autoComplete (answer, options, matches, 1); // Hard-coded 1. } while (matches.size () != 1); return matches[0] == STRING_UTIL_CONFIRM_YES ? true : false; }
void ACLineEdit::autoComplete() { if(mMatches.size()) { QString t = mMatches.front(); mMatches.pop_front(); mMatches.append(t); pushCompletor(t); if(mLeft.isEmpty()) { setText(t + ": " + mRight); setCursorPosition(t.length() + 2); } else { setText(mLeft + t + mRight); setCursorPosition(mLeft.length() + t.length()); } return; } QString _text = text(), t = _text.left(cursorPosition()); int ix = t.lastIndexOf(' ') + 1; t = t.mid(ix); QStringList::iterator it, end = mCompletors.end(); for(it = mCompletors.begin(); it != end; it ++) if((*it).startsWith(t, Qt::CaseInsensitive)) mMatches << *it; mLeft = _text.left(ix); mRight = _text.mid(ix + t.length()); if(mMatches.size()) autoComplete(); }
int main(int argc, char *argv[]) { int continuer = 1; Commande *commande = malloc(sizeof(commande)); initialiseCommande(commande); // signal(SIGINT, interrupt); Niveau *niveau = malloc(sizeof(niveau)); decompression(choixNiveau(argc, argv), commande, niveau); /*** */ struct sigaction act; memset (&act, '\0', sizeof(act)); /* Use the sa_sigaction field because the handles has two additional parameters */ act.sa_sigaction = &hdl; /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */ act.sa_flags = SA_SIGINFO; if (sigaction(SIGINT, &act, NULL) < 0) { perror ("sigaction"); return 1; } /**** */ int ch; int finCommande = 0; initscr(); idlok(stdscr, TRUE); scrollok(stdscr, TRUE); cbreak(); noecho(); keypad(stdscr, TRUE); intrflush(stdscr, FALSE); printw("nom : %s\n", niveau->nom); int x, y; int nbAppuiUp = 0; char *saisie; while(continuer){ finCommande = 0; saisie = malloc(TAILLE_MAX_COMMANDE*sizeof(char)); debutLigne(commande, niveau); while(finCommande == 0){ ch = wgetch(stdscr); if(ch != KEY_UP && ch !=KEY_DOWN) nbAppuiUp = 0; if (ch == KEY_BACKSPACE) { getyx(stdscr, y, x); if(x > strlen(commande->directory)+3){ move(y, x-1); delch(); strcpy(saisie, substr(saisie, 0, strlen(saisie)-1)); } } else if(ch == KEY_LEFT){ getyx(stdscr, y, x); move(y, x-1); } else if(ch == KEY_RIGHT){ getyx(stdscr, y, x); move(y, x+1); } else if (ch == KEY_UP) { nbAppuiUp++; String *temp = malloc(sizeof(String)); temp = niveau->history->premier; if (temp->suivant != NULL) { int i = 0; while(i < nbAppuiUp && temp->suivant != NULL){ temp = temp->suivant; i++; } free(saisie); saisie = malloc(sizeof(char)*TAILLE_MAX_COMMANDE); strcpy(saisie, temp->string); effaceCommande(commande); printw("%s", saisie); } } else if (ch == KEY_DOWN) { nbAppuiUp--; String *temp = malloc(sizeof(String)); temp = niveau->history->premier; if (temp->suivant != NULL) { int i = 0; while(i < nbAppuiUp && temp->suivant != NULL){ temp = temp->suivant; i++; } free(saisie); saisie = malloc(sizeof(char)*TAILLE_MAX_COMMANDE); strcpy(saisie, temp->string); effaceCommande(commande); printw("%s", saisie); } } else if(ch == KEY_DC){ delch(); strcpy(saisie, substr(saisie, 0, strlen(saisie)-1)); } else if(ch == '\t'){ effaceCommande(commande); char *essai = malloc(sizeof(char)*TAILLE_MAX_COMMANDE); if(strlen(autoComplete(saisie, niveau)) == 0) finCommande = 1; else{ strcpy(saisie, strcat(saisie, autoComplete(saisie, niveau))); printw("%s", saisie); } } else if(ch == '\n'){ finCommande = 1; printw("\n"); } else{ printw("%c", ch); sprintf(saisie, "%s%c", saisie, ch); } } strcpy(commande->commande, saisie); execution(commande, niveau); // free(saisie); } endwin(); return 0; }
int CmdCalendar::execute (std::string& output) { int rc = 0; // Each month requires 28 text columns width. See how many will actually // fit. But if a preference is specified, and it fits, use it. int width = context.getWidth (); int preferredMonthsPerLine = (context.config.getInteger ("monthsperline")); int monthsThatFit = width / 26; int monthsPerLine = monthsThatFit; if (preferredMonthsPerLine != 0 && preferredMonthsPerLine < monthsThatFit) monthsPerLine = preferredMonthsPerLine; // Load the pending tasks. handleRecurrence (); std::vector <Task> tasks = context.tdb2.pending.get_tasks (); Date today; bool getpendingdate = false; int monthsToDisplay = 1; int mFrom = today.month (); int yFrom = today.year (); int mTo = mFrom; int yTo = yFrom; // Defaults. monthsToDisplay = monthsPerLine; mFrom = today.month (); yFrom = today.year (); // Set up a vector of commands (1), for autoComplete. std::vector <std::string> commandNames; commandNames.push_back ("calendar"); // Set up a vector of keywords, for autoComplete. std::vector <std::string> keywordNames; keywordNames.push_back ("due"); // Set up a vector of months, for autoComplete. std::vector <std::string> monthNames; for (int i = 1; i <= 12; ++i) monthNames.push_back (lowerCase (Date::monthName (i))); // For autoComplete results. std::vector <std::string> matches; // Look at all args, regardless of sequence. int argMonth = 0; int argYear = 0; bool argWholeYear = false; std::vector <std::string> words = context.cli.getWords (); std::vector <std::string>::iterator arg; for (arg = words.begin (); arg != words.end (); ++arg) { // Some version of "calendar". if (autoComplete (lowerCase (*arg), commandNames, matches, context.config.getInteger ("abbreviation.minimum")) == 1) continue; // "due". else if (autoComplete (lowerCase (*arg), keywordNames, matches, context.config.getInteger ("abbreviation.minimum")) == 1) getpendingdate = true; // "y". else if (lowerCase (*arg) == "y") argWholeYear = true; // YYYY. else if (Lexer::isAllDigits (*arg) && arg->length () == 4) argYear = strtol (arg->c_str (), NULL, 10); // MM. else if (Lexer::isAllDigits (*arg) && arg->length () <= 2) { argMonth = strtol (arg->c_str (), NULL, 10); if (argMonth < 1 || argMonth > 12) throw format (STRING_CMD_CAL_BAD_MONTH, *arg); } // "January" etc. else if (autoComplete (lowerCase (*arg), monthNames, matches, context.config.getInteger ("abbreviation.minimum")) == 1) { argMonth = Date::monthOfYear (matches[0]); if (argMonth == -1) throw format (STRING_CMD_CAL_BAD_MONTH, *arg); } else throw format (STRING_CMD_CAL_BAD_ARG, *arg); } // Supported combinations: // // Command line monthsToDisplay mFrom yFrom getpendingdate // ------------ --------------- ----- ----- -------------- // cal monthsPerLine today today false // cal y 12 today today false // cal due monthsPerLine today today true // cal YYYY 12 1 arg false // cal due y 12 today today true // cal MM YYYY monthsPerLine arg arg false // cal MM YYYY y 12 arg arg false if (argWholeYear || (argYear && !argMonth && !argWholeYear)) monthsToDisplay = 12; if (!argMonth && argYear) mFrom = 1; else if (argMonth && argYear) mFrom = argMonth; if (argYear) yFrom = argYear; // Now begin the data subset and rendering. int countDueDates = 0; if (getpendingdate == true) { // Find the oldest pending due date. Date oldest (12, 31, 2037); std::vector <Task>::iterator task; for (task = tasks.begin (); task != tasks.end (); ++task) { if (task->getStatus () == Task::pending) { if (task->has ("due") && !task->hasTag ("nocal")) { ++countDueDates; Date d (task->get ("due")); if (d < oldest) oldest = d; } } } mFrom = oldest.month(); yFrom = oldest.year(); } if (context.config.getBoolean ("calendar.offset")) { int moffset = context.config.getInteger ("calendar.offset.value") % 12; int yoffset = context.config.getInteger ("calendar.offset.value") / 12; mFrom += moffset; yFrom += yoffset; if (mFrom < 1) { mFrom += 12; yFrom--; } else if (mFrom > 12) { mFrom -= 12; yFrom++; } } mTo = mFrom + monthsToDisplay - 1; yTo = yFrom; if (mTo > 12) { mTo -= 12; yTo++; } int details_yFrom = yFrom; int details_mFrom = mFrom; std::stringstream out; out << "\n"; while (yFrom < yTo || (yFrom == yTo && mFrom <= mTo)) { int nextM = mFrom; int nextY = yFrom; // Print month headers (cheating on the width settings, yes) for (int i = 0 ; i < monthsPerLine ; i++) { std::string month = Date::monthName (nextM); // 12345678901234567890123456 = 26 chars wide // ^^ = center // <-------> = 13 - (month.length / 2) + 1 // <------> = 26 - above // +--------------------------+ // | July 2009 | // | Mo Tu We Th Fr Sa Su | // | 27 1 2 3 4 5 | // | 28 6 7 8 9 10 11 12 | // | 29 13 14 15 16 17 18 19 | // | 30 20 21 22 23 24 25 26 | // | 31 27 28 29 30 31 | // +--------------------------+ int totalWidth = 26; int labelWidth = month.length () + 5; // 5 = " 2009" int leftGap = (totalWidth / 2) - (labelWidth / 2); int rightGap = totalWidth - leftGap - labelWidth; out << std::setw (leftGap) << ' ' << month << ' ' << nextY << std::setw (rightGap) << ' '; if (++nextM > 12) { nextM = 1; nextY++; } } out << "\n" << optionalBlankLine () << renderMonths (mFrom, yFrom, today, tasks, monthsPerLine) << "\n"; mFrom += monthsPerLine; if (mFrom > 12) { mFrom -= 12; ++yFrom; } } Color color_today (context.config.get ("color.calendar.today")); Color color_due (context.config.get ("color.calendar.due")); Color color_duetoday (context.config.get ("color.calendar.due.today")); Color color_overdue (context.config.get ("color.calendar.overdue")); Color color_weekend (context.config.get ("color.calendar.weekend")); Color color_holiday (context.config.get ("color.calendar.holiday")); Color color_weeknumber (context.config.get ("color.calendar.weeknumber")); Color color_label (context.config.get ("color.label")); if (context.color () && context.config.getBoolean ("calendar.legend")) out << "Legend: " << color_today.colorize ("today") << ", " << color_due.colorize ("due") << ", " << color_duetoday.colorize ("due-today") << ", " << color_overdue.colorize ("overdue") << ", " << color_weekend.colorize ("weekend") << ", " << color_holiday.colorize ("holiday") << ", " << color_weeknumber.colorize ("weeknumber") << "." << optionalBlankLine () << "\n"; if (context.config.get ("calendar.details") == "full" || context.config.get ("calendar.holidays") == "full") { --details_mFrom; if (details_mFrom == 0) { details_mFrom = 12; --details_yFrom; } int details_dFrom = Date::daysInMonth (details_mFrom, details_yFrom); ++mTo; if (mTo == 13) { mTo = 1; ++yTo; } Date date_after (details_mFrom, details_dFrom, details_yFrom); std::string after = date_after.toString (context.config.get ("dateformat")); Date date_before (mTo, 1, yTo); std::string before = date_before.toString (context.config.get ("dateformat")); // Table with due date information if (context.config.get ("calendar.details") == "full") { // Assert that 'report' is a valid report. std::string report = context.config.get ("calendar.details.report"); if (context.commands.find (report) == context.commands.end ()) throw std::string (STRING_ERROR_DETAILS); // If the executable was "cal" or equivalent, replace it with "task". std::string executable = context.cli._args[0].attribute ("raw"); std::string::size_type cal = executable.find ("cal"); if (cal != std::string::npos) executable = executable.substr (0, cal) + PACKAGE; std::vector <std::string> args; args.push_back ("rc:" + context.rc_file._data); args.push_back ("rc.due:0"); args.push_back ("rc.verbose:label,affected,blank"); args.push_back ("due.after:" + after); args.push_back ("due.before:" + before); args.push_back ("-nocal"); args.push_back (report); std::string output; ::execute (executable, args, "", output); out << output; } // Table with holiday information if (context.config.get ("calendar.holidays") == "full") { ViewText holTable; holTable.width (context.getWidth ()); holTable.add (Column::factory ("string", STRING_CMD_CAL_LABEL_DATE)); holTable.add (Column::factory ("string", STRING_CMD_CAL_LABEL_HOL)); holTable.colorHeader (color_label); Config::const_iterator it; std::map <time_t, std::vector<std::string>> hm; // we need to store multiple holidays per day for (it = context.config.begin (); it != context.config.end (); ++it) if (it->first.substr (0, 8) == "holiday.") if (it->first.substr (it->first.size () - 4) == "name") { std::string holName = context.config.get ("holiday." + it->first.substr (8, it->first.size () - 13) + ".name"); std::string holDate = context.config.get ("holiday." + it->first.substr (8, it->first.size () - 13) + ".date"); Date hDate (holDate.c_str (), context.config.get ("dateformat.holiday")); if (date_after < hDate && hDate < date_before) { hm[hDate.toEpoch()].push_back(holName); } } std::string format = context.config.get ("report." + context.config.get ("calendar.details.report") + ".dateformat"); if (format == "") format = context.config.get ("dateformat.report"); if (format == "") format = context.config.get ("dateformat"); std::map <time_t, std::vector<std::string>>::iterator hm_it; for (hm_it = hm.begin(); hm_it != hm.end(); ++hm_it) { std::vector <std::string> v = hm_it->second; Date hDate (hm_it->first); std::string d = hDate.toString (format); for (size_t i = 0; i < v.size(); i++) { int row = holTable.addRow (); holTable.set (row, 0, d); holTable.set (row, 1, v[i]); } } out << optionalBlankLine () << holTable.render () << "\n"; } } output = out.str (); return rc; }
//////////////////////////////////////////////////////////////////////////////// // If the input string looks like a relative date, determine that date, set _t // and return true. // // What is a relative date? All of the following should be recognizable, and // converted to an absolute date: // wednesday // fri // 23rd // today // tomorrow // yesterday // eow (end of week) // eom (end of month) // eoy (end of year) // now bool Date::isRelativeDate (const std::string& input) { std::string in (lowerCase (input)); Date today; std::vector <std::string> supported; for (unsigned int i = 0; i < NUM_RELATIVES; ++i) supported.push_back (relatives[i]); // Hard-coded 3, despite rc.abbreviation.minimum. std::vector <std::string> matches; if (autoComplete (in, supported, matches, 3) == 1) { std::string found = matches[0]; // If day name. int dow; if ((dow = Date::dayOfWeek (found)) != -1 || found == "eow" || found == "eoww" || found == "eocw" || found == "sow" || found == "soww" || found == "socw") { if (found == "eow" || found == "eoww") dow = 5; if (found == "eocw") dow = (Date::dayOfWeek (context.config.get ("weekstart")) + 6) % 7; if (found == "sow" || found == "soww") dow = 1; if (found == "socw") dow = Date::dayOfWeek (context.config.get ("weekstart")); if (today.dayOfWeek () >= dow) today += (dow - today.dayOfWeek () + 7) * 86400; else today += (dow - today.dayOfWeek ()) * 86400; int m, d, y; today.toMDY (m, d, y); Date then (m, d, y); _t = then._t; return true; } else if (found == "today") { Date then (today.month (), today.day (), today.year ()); _t = then._t; return true; } else if (found == "tomorrow") { Date then (today.month (), today.day (), today.year ()); _t = then._t + 86400; return true; } else if (found == "yesterday") { Date then (today.month (), today.day (), today.year ()); _t = then._t - 86400; return true; } else if (found == "eom") { Date then (today.month (), daysInMonth (today.month (), today.year ()), today.year ()); _t = then._t; return true; } else if (found == "eoq") { int eoq_month = today.month () + 2 - (today.month () - 1) % 3; Date then (eoq_month, daysInMonth (eoq_month, today.year ()), today.year ()); _t = then._t; return true; } else if (found == "eoy") { Date then (12, 31, today.year ()); _t = then._t; return true; } else if (found == "som") { int m = today.month () + 1; int y = today.year (); if (m > 12) { m -=12; y++; } Date then (m, 1, y); _t = then._t; return true; } else if (found == "soq") { int m = today.month () + 3 - (today.month () - 1) % 3; int y = today.year (); if (m > 12) { m -=12; y++; } Date then (m , 1, y); _t = then._t; return true; } else if (found == "soy") { Date then (1, 1, today.year () + 1); _t = then._t; return true; } else if (found == "goodfriday") { Date then (Date::easter(today.year())); _t = then._t - 86400*2; return true; } else if (found == "easter") { Date then (Date::easter(today.year())); _t = then._t; return true; } else if (found == "eastermonday") { Date then (Date::easter(today.year())); _t = then._t + 86400; return true; } else if (found == "ascension") { Date then (Date::easter(today.year())); _t = then._t + 86400*39; return true; } else if (found == "pentecost") { Date then (Date::easter(today.year())); _t = then._t + 86400*49; return true; } else if (found == "midsommar") { for (int midsommar = 20; midsommar <= 26; midsommar++) { Date then (6, midsommar, today.year ()); if (6 == then.dayOfWeek ()) { _t = then._t; return true; } } } else if (found == "midsommarafton") { for (int midsommar = 19; midsommar <= 25; midsommar++) { Date then (6, midsommar, today.year ()); if (5 == then.dayOfWeek ()) { _t = then._t; return true; } } } else if (found == "now") { _t = time (NULL); return true; } else if (found == "later" || found == "someday") { Date then (1, 18, 2038); _t = then._t; return true; } } // Support "21st" to indicate the next date that is the 21st day. else if (input.length () <= 4 && isdigit (input[0])) { int number; std::string ordinal; if (isdigit (input[1])) { number = atoi (input.substr (0, 2).c_str ()); ordinal = lowerCase (input.substr (2)); } else { number = atoi (input.substr (0, 2).c_str ()); ordinal = lowerCase (input.substr (1)); } // Sanity check. if (number <= 31) { if (ordinal == "st" || ordinal == "nd" || ordinal == "rd" || ordinal == "th") { int m = today.month (); int d = today.day (); int y = today.year (); // If it is this month. if (d < number && number <= Date::daysInMonth (m, y)) { Date then (m, number, y); _t = then._t; return true; } do { m++; if (m > 12) { m = 1; y++; } } while (number > Date::daysInMonth (m, y)); Date then (m, number, y); _t = then._t; return true; } } } return false; }
void InputField::KeyboardEvent( const struct KeyboardEvent &ev ) { char c = GetPrintableCharForKeycode( ev.key ); if ( c >= 0x20 ) { // insert a character at the cursor and move the cursor along current.insert( cursorPos, 1, c ); numChars++; cursorPos++; } else if ( ev.key == SDLK_BACKSPACE ) { // remove the character before the cursor if ( cursorPos != 0 ) { current.erase( cursorPos - 1, 1 ); numChars--; cursorPos--; } } else if ( ev.key == SDLK_DELETE ) { // remove the character after the cursor if ( cursorPos != current.length() ) { current.erase( cursorPos, 1 ); numChars--; } } else if ( ev.key == SDLK_RETURN ) { // commit the current line to history, pass it to the command buffer and print it to console // no action to take if it's empty... if ( current.empty() ) { return; } // pass to command buffer if ( execute ) { execute( current.c_str() ); } // commit to history if ( !current.empty() ) { history.push_back( current ); } // make sure history index is reset historyIndex = 0u; historySeeking = false; // print to console console.Print( PrintLevel::Normal, ">%s\n", current.c_str() ); // clear the state Clear(); } else if ( ev.key == SDLK_LEFT ) { // move cursor left if ( cursorPos > 0 ) { cursorPos--; } } else if ( ev.key == SDLK_RIGHT ) { // move cursor right if ( cursorPos < numChars ) { cursorPos++; } } else if ( ev.key == SDLK_UP ) { if ( historySeeking ) { // if we're already seeking, it means history is not empty historyIndex++; ClampHistory(); } else { // not already seeking, see if we should commit the current line before seeking if ( !current.empty() ) { history.push_back( current ); } const size_t historySize = history.size(); if ( historySize ) { historySeeking = true; // now we're seeking historyIndex++; ClampHistory(); } } if ( historySeeking ) { Clear(); current = GetHistory( historyIndex ); // set the cursor pos to the end of the line cursorPos = numChars = current.length(); } } else if ( ev.key == SDLK_DOWN ) { if ( historySeeking ) { // if we're already seeking, it means history is not empty historyIndex--; if ( historyIndex == 0u ) { historySeeking = false; } ClampHistory(); } else { // not already seeking, see if we should commit the current line if ( !current.empty() ) { history.push_back( current ); } Clear(); } if ( historySeeking ) { current = GetHistory( historyIndex ); // set the cursor pos to the end of the line cursorPos = numChars = current.length(); } else { Clear(); } } else if ( ev.key == SDLK_TAB ) { if ( autoComplete ) { if ( const char *result = autoComplete( current.c_str() ) ) { current = result; cursorPos = numChars = current.length(); } } } }
ACLineEdit::ACLineEdit(QWidget * parent, const char * name) : QLineEdit(name, parent) { new QShortcut(Qt::Key_Tab, this, SLOT(autoComplete())); }
/** * Parse & find the next command. * * @param prompt The prompt to print. * * @return The command to execute, if one was found, NULL otherwise. */ const Command* nextCommand(struct Shell* self, const char* prompt) { size_t promptLen = strlen(prompt) + 7; int i; char in; // We reset the input status. self->cursor = 0; self->inputEnd = 0; self->usingHistory = 0; struct History* history = &self->history; printPrompt(self, prompt); // We set the whole string to null for safety. memset(self->buffer, 0, BUFFER_SIZE); while ((in = getchar()) != '\n') { // Check for control sequences, these are things like arrow keys and such. if (in == '\033') { if (getchar() == CSI) { // We know this! Yay! switch (getchar()) { case 'A': // Up if (history->current != history->start) { history->current--; if (history->current < 0) { history->current = HISTORY_SIZE - 1; } self->inputEnd = replaceInput( self, promptLen, history->input[history->current] ); self->cursor = self->inputEnd; self->usingHistory = 1; } break; case 'B': // Down if (self->usingHistory) { if (history->current == history->end) { self->usingHistory = 0; self->inputEnd = replaceInput(self, promptLen, self->buffer); } else { history->current = (history->current + 1) % HISTORY_SIZE; self->inputEnd = replaceInput( self, promptLen, history->input[history->current] ); } self->cursor = self->inputEnd; } break; case 'C': // Right if (self->cursor == self->inputEnd) { break; } updateCursor(self, promptLen, self->cursor + 1); break; case 'D': // Left if (self->cursor == 0) { break; } updateCursor(self, promptLen, self->cursor - 1); break; case 'H': // Home updateCursor(self, promptLen, 0); break; case 'F': // End updateCursor(self, promptLen, self->inputEnd); break; case CSI: //This is a function key in = getchar(); // We don't support this anymore (not from here at least) break; } } } else if (in == '\t') { if (self->usingHistory) { chooseCurrentEntry(self); } autoComplete(self, prompt); } else if (in == '\b') { if (self->usingHistory) { chooseCurrentEntry(self); } if (self->cursor > 0) { int destPos = self->cursor - 1; self->inputEnd--; // Move back once to step on the previous text updateCursor(self, promptLen, self->cursor - 1); for (i = self->cursor; i < self->inputEnd; i++) { self->buffer[i] = self->buffer[i + 1]; } // Set a space in the end to make sure we erase previous text self->buffer[self->inputEnd] = ' '; // Print out printf("%s", self->buffer + self->cursor); // The input actually ends one after (the space we inserted) self->cursor = self->inputEnd + 1; updateCursor(self, promptLen, destPos); // Make sure the buffer is always null terminated self->buffer[self->inputEnd] = 0; } } else if (!isspace(in) || in == ' ') { if (self->usingHistory) { chooseCurrentEntry(self); } addToInput(self, promptLen, &in, 1); } } if (self->usingHistory) { // This means enter was pressed while browsing the history // So let's take the current history entry as the input memcpy(self->buffer, history->input[history->current], BUFFER_SIZE); } updateCursor(self, promptLen, self->inputEnd); putchar('\n'); addToHistory(history, self->buffer); return findCommand(self->buffer); }
void Duration::parse (const std::string& input) { std::string lower_input = lowerCase (input); // Assume the ordinal is 1, but look for an integer, just in case. double value = 1; Nibbler n (lower_input); n.getNumber (value); if (value < 0.0) { _negative = true; value = -value; } else _negative = false; // If no units are provided, assume seconds. if (n.depleted ()) { _secs = (long) value; return; } std::string units; n.getUntilEOS (units); // Auto complete against all supported durations. std::vector <std::string> supported; for (unsigned int i = 0; i < NUM_DURATIONS; ++i) supported.push_back (durations[i]); _secs = 0; std::vector <std::string> matches; if (autoComplete (units, supported, matches, context.config.getInteger ("abbreviation.minimum")) == 1) { std::string match = matches[0]; if (match == "biannual") _secs = (int) (value * 86400 * 730); else if (match == "biyearly") _secs = (int) (value * 86400 * 730); else if (match == "yearly") _secs = (int) (value * 86400 * 365); else if (match == "annual") _secs = (int) (value * 86400 * 365); else if (match == "years") _secs = (int) (value * 86400 * 365); else if (match == "year") _secs = (int) (value * 86400 * 365); else if (match == "yrs") _secs = (int) (value * 86400 * 365); else if (match == "yr") _secs = (int) (value * 86400 * 365); else if (match == "y") _secs = (int) (value * 86400 * 365); else if (match == "semiannual") _secs = (int) (value * 86400 * 183); else if (match == "bimonthly") _secs = (int) (value * 86400 * 61); else if (match == "quarterly") _secs = (int) (value * 86400 * 91); else if (match == "quarters") _secs = (int) (value * 86400 * 91); else if (match == "qrtrs") _secs = (int) (value * 86400 * 91); else if (match == "qtrs") _secs = (int) (value * 86400 * 91); else if (match == "qtr") _secs = (int) (value * 86400 * 91); else if (match == "q") _secs = (int) (value * 86400 * 91); else if (match == "monthly") _secs = (int) (value * 86400 * 30); else if (match == "month") _secs = (int) (value * 86400 * 30); else if (match == "months") _secs = (int) (value * 86400 * 30); else if (match == "mnths") _secs = (int) (value * 86400 * 30); else if (match == "mos") _secs = (int) (value * 86400 * 30); else if (match == "mo") _secs = (int) (value * 86400 * 30); else if (match == "mths") _secs = (int) (value * 86400 * 30); else if (match == "mth") _secs = (int) (value * 86400 * 30); else if (match == "m") _secs = (int) (value * 86400 * 30); else if (match == "biweekly") _secs = (int) (value * 86400 * 14); else if (match == "fortnight") _secs = (int) (value * 86400 * 14); else if (match == "weekly") _secs = (int) (value * 86400 * 7); else if (match == "sennight") _secs = (int) (value * 86400 * 7); else if (match == "weeks") _secs = (int) (value * 86400 * 7); else if (match == "week") _secs = (int) (value * 86400 * 7); else if (match == "wks") _secs = (int) (value * 86400 * 7); else if (match == "wk") _secs = (int) (value * 86400 * 7); else if (match == "w") _secs = (int) (value * 86400 * 7); else if (match == "daily") _secs = (int) (value * 86400 * 1); else if (match == "day") _secs = (int) (value * 86400 * 1); else if (match == "weekdays") _secs = (int) (value * 86400 * 1); else if (match == "days") _secs = (int) (value * 86400 * 1); else if (match == "d") _secs = (int) (value * 86400 * 1); else if (match == "hours") _secs = (int) (value * 3600); else if (match == "hour") _secs = (int) (value * 3600); else if (match == "hrs") _secs = (int) (value * 3600); else if (match == "hr") _secs = (int) (value * 3600); else if (match == "h") _secs = (int) (value * 3600); else if (match == "minutes") _secs = (int) (value * 60); else if (match == "mins") _secs = (int) (value * 60); else if (match == "min") _secs = (int) (value * 60); else if (match == "seconds") _secs = (int) value; else if (match == "secs") _secs = (int) value; else if (match == "sec") _secs = (int) value; else if (match == "s") _secs = (int) value; else if (match == "-") _secs = 0; } if (_secs == 0) throw ::format (STRING_DURATION_UNRECOGNIZED, input); }
virtual void customSetup(void) { QMenu *edit = toMainWidget()->getEditMenu(); edit->addSeparator(); IncMenu = edit->addMenu( qApp->translate("toEditExtensionTool", "Incremental Search")); IncrementalSearch = IncMenu->addAction(qApp->translate("toEditExtensionTool", "Forward"), &toEditExtensionsSingle::Instance(), SLOT(searchForward())); IncrementalSearch->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_S); ReverseSearch = IncMenu->addAction(qApp->translate("toEditExtensionTool", "Backward"), &toEditExtensionsSingle::Instance(), SLOT(searchBackward())); ReverseSearch->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_R); // ------------------------------ indentation menu IndentMenu = edit->addMenu( qApp->translate("toEditExtensionTool", "Auto Indent")); IndentBlock = IndentMenu->addAction(qApp->translate( "toEditExtensionTool", "Selection"), &toEditExtensionsSingle::Instance(), SLOT(autoIndentBlock())); IndentBlock->setShortcut(Qt::CTRL + + Qt::ALT + Qt::Key_I); IndentBuffer = IndentMenu->addAction(qApp->translate( "toEditExtensionTool", "Editor"), &toEditExtensionsSingle::Instance(), SLOT(autoIndentBuffer())); IndentBuffer->setShortcut(Qt::CTRL + Qt::ALT + Qt::SHIFT + Qt::Key_I); IndentMenu->addSeparator(); ObsBlock = IndentMenu->addAction(qApp->translate( "toEditExtensionTool", "Obfuscate Selection"), &toEditExtensionsSingle::Instance(), SLOT(obfuscateBlock())); ObsBuffer = IndentMenu->addAction(qApp->translate("toEditExtensionTool", "Obfuscate Editor"), &toEditExtensionsSingle::Instance(), SLOT(obfuscateBuffer())); // ------------------------------ case menu CaseMenu = edit->addMenu( qApp->translate("toEditExtensionTool", "Modify Case")); UpperCase = CaseMenu->addAction(qApp->translate("toEditExtensionTool", "Upper"), &toEditExtensionsSingle::Instance(), SLOT(upperCase())); UpperCase->setShortcut(Qt::CTRL + Qt::Key_U); LowerCase = CaseMenu->addAction(qApp->translate("toEditExtensionTool", "Lower"), &toEditExtensionsSingle::Instance(), SLOT(lowerCase())); LowerCase->setShortcut(Qt::CTRL + Qt::Key_L); // bookmark menu BookmarkMenu = edit->addMenu(qApp->translate("toEditExtensionTool", "Bookmarks")); BookmarkSwitchAct = BookmarkMenu->addAction("Add/Remove Bookmark", &toEditExtensionsSingle::Instance(), SLOT(bookmarkSwitch())); BookmarkSwitchAct->setShortcut(Qt::CTRL + Qt::Key_B); BookmarkPrevAct = BookmarkMenu->addAction("Go to previous Bookmark", &toEditExtensionsSingle::Instance(), SLOT(bookmarkPrev())); BookmarkPrevAct->setShortcut(Qt::ALT + Qt::Key_PageUp); BookmarkNextAct = BookmarkMenu->addAction("Go to next Bookmark", &toEditExtensionsSingle::Instance(), SLOT(bookmarkNext())); BookmarkNextAct->setShortcut(Qt::ALT + Qt::Key_PageDown); // EOL menu EolMenu = edit->addMenu(qApp->translate("toEditExtensionTool", "Convert End of Lines to")); EolUnixAct = EolMenu->addAction("UNIX", &toEditExtensionsSingle::Instance(), SLOT(convertEol())); EolMacAct = EolMenu->addAction("Mac OS X", &toEditExtensionsSingle::Instance(), SLOT(convertEol())); EolWindowsAct = EolMenu->addAction("MS Windows", &toEditExtensionsSingle::Instance(), SLOT(convertEol())); // ------------------------------ etc Indent = edit->addAction( QIcon(QPixmap(const_cast<const char**>(indent_xpm))), qApp->translate("toEditExtensionTool", "Indent Block"), &toEditExtensionsSingle::Instance(), SLOT(indentBlock())); #ifndef Q_WS_MAC Indent->setShortcut(Qt::ALT + Qt::Key_Right); #endif Deindent = edit->addAction( QIcon(QPixmap(const_cast<const char**>(deindent_xpm))), qApp->translate("toEditExtensionTool", "De-indent Block"), &toEditExtensionsSingle::Instance(), SLOT(deindentBlock())); #ifndef Q_WS_MAC Deindent->setShortcut(Qt::ALT + Qt::Key_Left); #endif Quote = edit->addAction(qApp->translate("toEditExtensionTool", "Quote Selection"), &toEditExtensionsSingle::Instance(), SLOT(quoteBlock())); UnQuote = edit->addAction(qApp->translate("toEditExtensionTool", "UnQuote Selection"), &toEditExtensionsSingle::Instance(), SLOT(unquoteBlock())); Comment = edit->addAction(qApp->translate("toEditExtensionTool", "Comment or Uncomment"), &toEditExtensionsSingle::Instance(), SLOT(handleComment()), Qt::CTRL + Qt::Key_D); GotoLine = edit->addAction(qApp->translate("toEditExtensionTool", "Goto Line"), &toEditExtensionsSingle::Instance(), SLOT(gotoLine())); GotoLine->setShortcut(Qt::CTRL + Qt::Key_G); AutoComplete = edit->addAction( qApp->translate("toEditExtensionTool", "Complete"), &toEditExtensionsSingle::Instance(), SLOT(autoComplete())); AutoComplete->setShortcut(Qt::CTRL + Qt::Key_Space); // add buttons to main window // disabled due the problems in the state of toolbars // toMainWidget()->addButtonApplication(Deindent); // toMainWidget()->addButtonApplication(Indent); toEditExtensionsSingle::Instance().receivedFocus(NULL); connect(toMainWidget(), SIGNAL(editEnabled(bool)), &toEditExtensionsSingle::Instance(), SLOT(editEnabled(bool))); }