Merge branch 'master' into config

Conflicts:
	spec/app/project-spec.coffee
	src/extensions/wrap-guide/src/wrap-guide.coffee
This commit is contained in:
Corey Johnson & Nathan Sobo 2012-12-14 14:14:50 -08:00
commit 55dc3e1cdf
31 changed files with 1546 additions and 51 deletions

1
.gitignore vendored
View File

@ -8,3 +8,4 @@ build
.xcodebuild-info
node_modules
npm-debug.log
/tags

View File

@ -127,6 +127,10 @@ task :nof do
system %{find . -name *spec.coffee | grep -v atom-build | xargs sed -E -i "" "s/f+(it|describe) +(['\\"])/\\1 \\2/g"}
end
task :tags do
system %{ctags -R src/ native/}
end
def application_path
applications = FileList["#{BUILD_DIR}/**/Atom.app"]
if applications.size == 0

View File

@ -301,6 +301,10 @@
'native/v8_extensions/atom.h',
'native/v8_extensions/git.mm',
'native/v8_extensions/git.h',
'native/v8_extensions/readtags.h',
'native/v8_extensions/readtags.c',
'native/v8_extensions/tags.h',
'native/v8_extensions/tags.mm',
],
# TODO(mark): For now, don't put any resources into this app. Its
# resources directory will be a symbolic link to the browser app's

View File

@ -4,6 +4,7 @@
#import "native/v8_extensions/onig_reg_exp.h"
#import "native/v8_extensions/onig_scanner.h"
#import "native/v8_extensions/git.h"
#import "native/v8_extensions/tags.h"
#import "native/message_translation.h"
#import "path_watcher.h"
#include <iostream>
@ -14,6 +15,7 @@ void AtomCefRenderProcessHandler::OnWebKitInitialized() {
new v8_extensions::OnigRegExp();
new v8_extensions::OnigScanner();
new v8_extensions::Git();
new v8_extensions::Tags();
}
void AtomCefRenderProcessHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
@ -31,7 +33,7 @@ bool AtomCefRenderProcessHandler::OnProcessMessageReceived(CefRefPtr<CefBrowser>
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) {
std::string name = message->GetName().ToString();
if (name == "reload") {
Reload(browser);
return true;
@ -73,28 +75,28 @@ void AtomCefRenderProcessHandler::Shutdown(CefRefPtr<CefBrowser> browser) {
bool AtomCefRenderProcessHandler::CallMessageReceivedHandler(CefRefPtr<CefV8Context> context, CefRefPtr<CefProcessMessage> message) {
context->Enter();
CefRefPtr<CefV8Value> atom = context->GetGlobal()->GetValue("atom");
CefRefPtr<CefV8Value> receiveFn = atom->GetValue("receiveMessageFromBrowserProcess");
CefV8ValueList arguments;
arguments.push_back(CefV8Value::CreateString(message->GetName().ToString()));
CefRefPtr<CefListValue> messageArguments = message->GetArgumentList();
if (messageArguments->GetSize() > 0) {
CefRefPtr<CefV8Value> data = CefV8Value::CreateArray(messageArguments->GetSize());
TranslateList(messageArguments, data);
arguments.push_back(data);
}
receiveFn->ExecuteFunction(atom, arguments);
context->Exit();
if (receiveFn->HasException()) {
std::cout << "ERROR: Exception in JS receiving message " << message->GetName().ToString() << "\n";
return false;
}
else {
return true;
return true;
}
}

View File

@ -14,7 +14,7 @@ public:
CefString& exception) OVERRIDE;
// Provide the reference counting implementation for this class.
IMPLEMENT_REFCOUNTING(Native);
IMPLEMENT_REFCOUNTING(Git);
};
}

View File

@ -16,8 +16,8 @@ var $native = {};
native function traverseTree(path, onFile, onDirectory);
$native.traverseTree = traverseTree;
native function getAllPathsAsync(path);
$native.getAllPathsAsync = getAllPathsAsync;
native function getAllFilePathsAsync(path, callback);
$native.getAllFilePathsAsync = getAllFilePathsAsync;
native function isFile(path);
$native.isFile = isFile;

View File

@ -103,7 +103,7 @@ bool Native::Execute(const CefString& name,
return true;
}
else if (name == "getAllPathsAsync") {
else if (name == "getAllFilePathsAsync") {
std::string argument = arguments[0]->GetStringValue().ToString();
CefRefPtr<CefV8Value> callback = arguments[1];
CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext();
@ -127,8 +127,7 @@ bool Native::Execute(const CefString& name,
}
bool isFile = entry->fts_info == FTS_NSOK;
bool isDir = entry->fts_info == FTS_D;
if (!isFile && !isDir) {
if (!isFile) {
continue;
}

View File

@ -0,0 +1,959 @@
/*
* $Id: readtags.c 592 2007-07-31 03:30:41Z dhiebert $
*
* Copyright (c) 1996-2003, Darren Hiebert
*
* This source code is released into the public domain.
*
* This module contains functions for reading tag files.
*/
/*
* INCLUDE FILES
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h> /* to declare off_t */
#include "readtags.h"
/*
* MACROS
*/
#define TAB '\t'
/*
* DATA DECLARATIONS
*/
typedef struct {
size_t size;
char *buffer;
} vstring;
/* Information about current tag file */
struct sTagFile {
/* has the file been opened and this structure initialized? */
short initialized;
/* format of tag file */
short format;
/* how is the tag file sorted? */
sortType sortMethod;
/* pointer to file structure */
FILE* fp;
/* file position of first character of `line' */
off_t pos;
/* size of tag file in seekable positions */
off_t size;
/* last line read */
vstring line;
/* name of tag in last line read */
vstring name;
/* defines tag search state */
struct {
/* file position of last match for tag */
off_t pos;
/* name of tag last searched for */
char *name;
/* length of name for partial matches */
size_t nameLength;
/* peforming partial match */
short partial;
/* ignoring case */
short ignorecase;
} search;
/* miscellaneous extension fields */
struct {
/* number of entries in `list' */
unsigned short max;
/* list of key value pairs */
tagExtensionField *list;
} fields;
/* buffers to be freed at close */
struct {
/* name of program author */
char *author;
/* name of program */
char *name;
/* URL of distribution */
char *url;
/* program version */
char *version;
} program;
};
/*
* DATA DEFINITIONS
*/
const char *const EmptyString = "";
const char *const PseudoTagPrefix = "!_";
/*
* FUNCTION DEFINITIONS
*/
/*
* Compare two strings, ignoring case.
* Return 0 for match, < 0 for smaller, > 0 for bigger
* Make sure case is folded to uppercase in comparison (like for 'sort -f')
* This makes a difference when one of the chars lies between upper and lower
* ie. one of the chars [ \ ] ^ _ ` for ascii. (The '_' in particular !)
*/
static int struppercmp (const char *s1, const char *s2)
{
int result;
do
{
result = toupper ((int) *s1) - toupper ((int) *s2);
} while (result == 0 && *s1++ != '\0' && *s2++ != '\0');
return result;
}
static int strnuppercmp (const char *s1, const char *s2, size_t n)
{
int result;
do
{
result = toupper ((int) *s1) - toupper ((int) *s2);
} while (result == 0 && --n > 0 && *s1++ != '\0' && *s2++ != '\0');
return result;
}
static int growString (vstring *s)
{
int result = 0;
size_t newLength;
char *newLine;
if (s->size == 0)
{
newLength = 128;
newLine = (char*) malloc (newLength);
*newLine = '\0';
}
else
{
newLength = 2 * s->size;
newLine = (char*) realloc (s->buffer, newLength);
}
if (newLine == NULL)
perror ("string too large");
else
{
s->buffer = newLine;
s->size = newLength;
result = 1;
}
return result;
}
/* Copy name of tag out of tag line */
static void copyName (tagFile *const file)
{
size_t length;
const char *end = strchr (file->line.buffer, '\t');
if (end == NULL)
{
end = strchr (file->line.buffer, '\n');
if (end == NULL)
end = strchr (file->line.buffer, '\r');
}
if (end != NULL)
length = end - file->line.buffer;
else
length = strlen (file->line.buffer);
while (length >= file->name.size)
growString (&file->name);
strncpy (file->name.buffer, file->line.buffer, length);
file->name.buffer [length] = '\0';
}
static int readTagLineRaw (tagFile *const file)
{
int result = 1;
int reReadLine;
/* If reading the line places any character other than a null or a
* newline at the last character position in the buffer (one less than
* the buffer size), then we must resize the buffer and reattempt to read
* the line.
*/
do
{
char *const pLastChar = file->line.buffer + file->line.size - 2;
char *line;
file->pos = ftell (file->fp);
reReadLine = 0;
*pLastChar = '\0';
line = fgets (file->line.buffer, (int) file->line.size, file->fp);
if (line == NULL)
{
/* read error */
if (! feof (file->fp))
perror ("readTagLine");
result = 0;
}
else if (*pLastChar != '\0' &&
*pLastChar != '\n' && *pLastChar != '\r')
{
/* buffer overflow */
growString (&file->line);
fseek (file->fp, file->pos, SEEK_SET);
reReadLine = 1;
}
else
{
size_t i = strlen (file->line.buffer);
while (i > 0 &&
(file->line.buffer [i - 1] == '\n' || file->line.buffer [i - 1] == '\r'))
{
file->line.buffer [i - 1] = '\0';
--i;
}
}
} while (reReadLine && result);
if (result)
copyName (file);
return result;
}
static int readTagLine (tagFile *const file)
{
int result;
do
{
result = readTagLineRaw (file);
} while (result && *file->name.buffer == '\0');
return result;
}
static tagResult growFields (tagFile *const file)
{
tagResult result = TagFailure;
unsigned short newCount = (unsigned short) 2 * file->fields.max;
tagExtensionField *newFields = (tagExtensionField*)
realloc (file->fields.list, newCount * sizeof (tagExtensionField));
if (newFields == NULL)
perror ("too many extension fields");
else
{
file->fields.list = newFields;
file->fields.max = newCount;
result = TagSuccess;
}
return result;
}
static void parseExtensionFields (tagFile *const file, tagEntry *const entry,
char *const string)
{
char *p = string;
while (p != NULL && *p != '\0')
{
while (*p == TAB)
*p++ = '\0';
if (*p != '\0')
{
char *colon;
char *field = p;
p = strchr (p, TAB);
if (p != NULL)
*p++ = '\0';
colon = strchr (field, ':');
if (colon == NULL)
entry->kind = field;
else
{
const char *key = field;
const char *value = colon + 1;
*colon = '\0';
if (strcmp (key, "kind") == 0)
entry->kind = value;
else if (strcmp (key, "file") == 0)
entry->fileScope = 1;
else if (strcmp (key, "line") == 0)
entry->address.lineNumber = atol (value);
else
{
if (entry->fields.count == file->fields.max)
growFields (file);
file->fields.list [entry->fields.count].key = key;
file->fields.list [entry->fields.count].value = value;
++entry->fields.count;
}
}
}
}
}
static void parseTagLine (tagFile *file, tagEntry *const entry)
{
int i;
char *p = file->line.buffer;
char *tab = strchr (p, TAB);
entry->fields.list = NULL;
entry->fields.count = 0;
entry->kind = NULL;
entry->fileScope = 0;
entry->name = p;
if (tab != NULL)
{
*tab = '\0';
p = tab + 1;
entry->file = p;
tab = strchr (p, TAB);
if (tab != NULL)
{
int fieldsPresent;
*tab = '\0';
p = tab + 1;
if (*p == '/' || *p == '?')
{
/* parse pattern */
int delimiter = *(unsigned char*) p;
entry->address.lineNumber = 0;
entry->address.pattern = p;
do
{
p = strchr (p + 1, delimiter);
} while (p != NULL && *(p - 1) == '\\');
if (p == NULL)
{
/* invalid pattern */
}
else
++p;
}
else if (isdigit ((int) *(unsigned char*) p))
{
/* parse line number */
entry->address.pattern = p;
entry->address.lineNumber = atol (p);
while (isdigit ((int) *(unsigned char*) p))
++p;
}
else
{
/* invalid pattern */
}
fieldsPresent = (strncmp (p, ";\"", 2) == 0);
*p = '\0';
if (fieldsPresent)
parseExtensionFields (file, entry, p + 2);
}
}
if (entry->fields.count > 0)
entry->fields.list = file->fields.list;
for (i = entry->fields.count ; i < file->fields.max ; ++i)
{
file->fields.list [i].key = NULL;
file->fields.list [i].value = NULL;
}
}
static char *duplicate (const char *str)
{
char *result = NULL;
if (str != NULL)
{
result = strdup (str);
if (result == NULL)
perror (NULL);
}
return result;
}
static void readPseudoTags (tagFile *const file, tagFileInfo *const info)
{
fpos_t startOfLine;
const size_t prefixLength = strlen (PseudoTagPrefix);
if (info != NULL)
{
info->file.format = 1;
info->file.sort = TAG_UNSORTED;
info->program.author = NULL;
info->program.name = NULL;
info->program.url = NULL;
info->program.version = NULL;
}
while (1)
{
fgetpos (file->fp, &startOfLine);
if (! readTagLine (file))
break;
if (strncmp (file->line.buffer, PseudoTagPrefix, prefixLength) != 0)
break;
else
{
tagEntry entry;
const char *key, *value;
parseTagLine (file, &entry);
key = entry.name + prefixLength;
value = entry.file;
if (strcmp (key, "TAG_FILE_SORTED") == 0)
file->sortMethod = (sortType) atoi (value);
else if (strcmp (key, "TAG_FILE_FORMAT") == 0)
file->format = (short) atoi (value);
else if (strcmp (key, "TAG_PROGRAM_AUTHOR") == 0)
file->program.author = duplicate (value);
else if (strcmp (key, "TAG_PROGRAM_NAME") == 0)
file->program.name = duplicate (value);
else if (strcmp (key, "TAG_PROGRAM_URL") == 0)
file->program.url = duplicate (value);
else if (strcmp (key, "TAG_PROGRAM_VERSION") == 0)
file->program.version = duplicate (value);
if (info != NULL)
{
info->file.format = file->format;
info->file.sort = file->sortMethod;
info->program.author = file->program.author;
info->program.name = file->program.name;
info->program.url = file->program.url;
info->program.version = file->program.version;
}
}
}
fsetpos (file->fp, &startOfLine);
}
static void gotoFirstLogicalTag (tagFile *const file)
{
fpos_t startOfLine;
const size_t prefixLength = strlen (PseudoTagPrefix);
rewind (file->fp);
while (1)
{
fgetpos (file->fp, &startOfLine);
if (! readTagLine (file))
break;
if (strncmp (file->line.buffer, PseudoTagPrefix, prefixLength) != 0)
break;
}
fsetpos (file->fp, &startOfLine);
}
static tagFile *initialize (const char *const filePath, tagFileInfo *const info)
{
tagFile *result = (tagFile*) calloc ((size_t) 1, sizeof (tagFile));
if (result != NULL)
{
growString (&result->line);
growString (&result->name);
result->fields.max = 20;
result->fields.list = (tagExtensionField*) calloc (
result->fields.max, sizeof (tagExtensionField));
result->fp = fopen (filePath, "r");
if (result->fp == NULL)
{
free (result);
result = NULL;
info->status.error_number = errno;
}
else
{
fseek (result->fp, 0, SEEK_END);
result->size = ftell (result->fp);
rewind (result->fp);
readPseudoTags (result, info);
info->status.opened = 1;
result->initialized = 1;
}
}
return result;
}
static void terminate (tagFile *const file)
{
fclose (file->fp);
free (file->line.buffer);
free (file->name.buffer);
free (file->fields.list);
if (file->program.author != NULL)
free (file->program.author);
if (file->program.name != NULL)
free (file->program.name);
if (file->program.url != NULL)
free (file->program.url);
if (file->program.version != NULL)
free (file->program.version);
if (file->search.name != NULL)
free (file->search.name);
memset (file, 0, sizeof (tagFile));
free (file);
}
static tagResult readNext (tagFile *const file, tagEntry *const entry)
{
tagResult result;
if (file == NULL || ! file->initialized)
result = TagFailure;
else if (! readTagLine (file))
result = TagFailure;
else
{
if (entry != NULL)
parseTagLine (file, entry);
result = TagSuccess;
}
return result;
}
static const char *readFieldValue (
const tagEntry *const entry, const char *const key)
{
const char *result = NULL;
int i;
if (strcmp (key, "kind") == 0)
result = entry->kind;
else if (strcmp (key, "file") == 0)
result = EmptyString;
else for (i = 0 ; i < entry->fields.count && result == NULL ; ++i)
if (strcmp (entry->fields.list [i].key, key) == 0)
result = entry->fields.list [i].value;
return result;
}
static int readTagLineSeek (tagFile *const file, const off_t pos)
{
int result = 0;
if (fseek (file->fp, pos, SEEK_SET) == 0)
{
result = readTagLine (file); /* read probable partial line */
if (pos > 0 && result)
result = readTagLine (file); /* read complete line */
}
return result;
}
static int nameComparison (tagFile *const file)
{
int result;
if (file->search.ignorecase)
{
if (file->search.partial)
result = strnuppercmp (file->search.name, file->name.buffer,
file->search.nameLength);
else
result = struppercmp (file->search.name, file->name.buffer);
}
else
{
if (file->search.partial)
result = strncmp (file->search.name, file->name.buffer,
file->search.nameLength);
else
result = strcmp (file->search.name, file->name.buffer);
}
return result;
}
static void findFirstNonMatchBefore (tagFile *const file)
{
#define JUMP_BACK 512
int more_lines;
int comp;
off_t start = file->pos;
off_t pos = start;
do
{
if (pos < (off_t) JUMP_BACK)
pos = 0;
else
pos = pos - JUMP_BACK;
more_lines = readTagLineSeek (file, pos);
comp = nameComparison (file);
} while (more_lines && comp == 0 && pos > 0 && pos < start);
}
static tagResult findFirstMatchBefore (tagFile *const file)
{
tagResult result = TagFailure;
int more_lines;
off_t start = file->pos;
findFirstNonMatchBefore (file);
do
{
more_lines = readTagLine (file);
if (nameComparison (file) == 0)
result = TagSuccess;
} while (more_lines && result != TagSuccess && file->pos < start);
return result;
}
static tagResult findBinary (tagFile *const file)
{
tagResult result = TagFailure;
off_t lower_limit = 0;
off_t upper_limit = file->size;
off_t last_pos = 0;
off_t pos = upper_limit / 2;
while (result != TagSuccess)
{
if (! readTagLineSeek (file, pos))
{
/* in case we fell off end of file */
result = findFirstMatchBefore (file);
break;
}
else if (pos == last_pos)
{
/* prevent infinite loop if we backed up to beginning of file */
break;
}
else
{
const int comp = nameComparison (file);
last_pos = pos;
if (comp < 0)
{
upper_limit = pos;
pos = lower_limit + ((upper_limit - lower_limit) / 2);
}
else if (comp > 0)
{
lower_limit = pos;
pos = lower_limit + ((upper_limit - lower_limit) / 2);
}
else if (pos == 0)
result = TagSuccess;
else
result = findFirstMatchBefore (file);
}
}
return result;
}
static tagResult findSequential (tagFile *const file)
{
tagResult result = TagFailure;
if (file->initialized)
{
while (result == TagFailure && readTagLine (file))
{
if (nameComparison (file) == 0)
result = TagSuccess;
}
}
return result;
}
static tagResult find (tagFile *const file, tagEntry *const entry,
const char *const name, const int options)
{
tagResult result;
if (file->search.name != NULL)
free (file->search.name);
file->search.name = duplicate (name);
file->search.nameLength = strlen (name);
file->search.partial = (options & TAG_PARTIALMATCH) != 0;
file->search.ignorecase = (options & TAG_IGNORECASE) != 0;
fseek (file->fp, 0, SEEK_END);
file->size = ftell (file->fp);
rewind (file->fp);
if ((file->sortMethod == TAG_SORTED && !file->search.ignorecase) ||
(file->sortMethod == TAG_FOLDSORTED && file->search.ignorecase))
{
#ifdef DEBUG
printf ("<performing binary search>\n");
#endif
result = findBinary (file);
}
else
{
#ifdef DEBUG
printf ("<performing sequential search>\n");
#endif
result = findSequential (file);
}
if (result != TagSuccess)
file->search.pos = file->size;
else
{
file->search.pos = file->pos;
if (entry != NULL)
parseTagLine (file, entry);
}
return result;
}
static tagResult findNext (tagFile *const file, tagEntry *const entry)
{
tagResult result;
if ((file->sortMethod == TAG_SORTED && !file->search.ignorecase) ||
(file->sortMethod == TAG_FOLDSORTED && file->search.ignorecase))
{
result = tagsNext (file, entry);
if (result == TagSuccess && nameComparison (file) != 0)
result = TagFailure;
}
else
{
result = findSequential (file);
if (result == TagSuccess && entry != NULL)
parseTagLine (file, entry);
}
return result;
}
/*
* EXTERNAL INTERFACE
*/
extern tagFile *tagsOpen (const char *const filePath, tagFileInfo *const info)
{
return initialize (filePath, info);
}
extern tagResult tagsSetSortType (tagFile *const file, const sortType type)
{
tagResult result = TagFailure;
if (file != NULL && file->initialized)
{
file->sortMethod = type;
result = TagSuccess;
}
return result;
}
extern tagResult tagsFirst (tagFile *const file, tagEntry *const entry)
{
tagResult result = TagFailure;
if (file != NULL && file->initialized)
{
gotoFirstLogicalTag (file);
result = readNext (file, entry);
}
return result;
}
extern tagResult tagsNext (tagFile *const file, tagEntry *const entry)
{
tagResult result = TagFailure;
if (file != NULL && file->initialized)
result = readNext (file, entry);
return result;
}
extern const char *tagsField (const tagEntry *const entry, const char *const key)
{
const char *result = NULL;
if (entry != NULL)
result = readFieldValue (entry, key);
return result;
}
extern tagResult tagsFind (tagFile *const file, tagEntry *const entry,
const char *const name, const int options)
{
tagResult result = TagFailure;
if (file != NULL && file->initialized)
result = find (file, entry, name, options);
return result;
}
extern tagResult tagsFindNext (tagFile *const file, tagEntry *const entry)
{
tagResult result = TagFailure;
if (file != NULL && file->initialized)
result = findNext (file, entry);
return result;
}
extern tagResult tagsClose (tagFile *const file)
{
tagResult result = TagFailure;
if (file != NULL && file->initialized)
{
terminate (file);
result = TagSuccess;
}
return result;
}
/*
* TEST FRAMEWORK
*/
#ifdef READTAGS_MAIN
static const char *TagFileName = "tags";
static const char *ProgramName;
static int extensionFields;
static int SortOverride;
static sortType SortMethod;
static void printTag (const tagEntry *entry)
{
int i;
int first = 1;
const char* separator = ";\"";
const char* const empty = "";
/* "sep" returns a value only the first time it is evaluated */
#define sep (first ? (first = 0, separator) : empty)
printf ("%s\t%s\t%s",
entry->name, entry->file, entry->address.pattern);
if (extensionFields)
{
if (entry->kind != NULL && entry->kind [0] != '\0')
printf ("%s\tkind:%s", sep, entry->kind);
if (entry->fileScope)
printf ("%s\tfile:", sep);
#if 0
if (entry->address.lineNumber > 0)
printf ("%s\tline:%lu", sep, entry->address.lineNumber);
#endif
for (i = 0 ; i < entry->fields.count ; ++i)
printf ("%s\t%s:%s", sep, entry->fields.list [i].key,
entry->fields.list [i].value);
}
putchar ('\n');
#undef sep
}
static void findTag (const char *const name, const int options)
{
tagFileInfo info;
tagEntry entry;
tagFile *const file = tagsOpen (TagFileName, &info);
if (file == NULL)
{
fprintf (stderr, "%s: cannot open tag file: %s: %s\n",
ProgramName, strerror (info.status.error_number), name);
exit (1);
}
else
{
if (SortOverride)
tagsSetSortType (file, SortMethod);
if (tagsFind (file, &entry, name, options) == TagSuccess)
{
do
{
printTag (&entry);
} while (tagsFindNext (file, &entry) == TagSuccess);
}
tagsClose (file);
}
}
static void listTags (void)
{
tagFileInfo info;
tagEntry entry;
tagFile *const file = tagsOpen (TagFileName, &info);
if (file == NULL)
{
fprintf (stderr, "%s: cannot open tag file: %s: %s\n",
ProgramName, strerror (info.status.error_number), TagFileName);
exit (1);
}
else
{
while (tagsNext (file, &entry) == TagSuccess)
printTag (&entry);
tagsClose (file);
}
}
const char *const Usage =
"Find tag file entries matching specified names.\n\n"
"Usage: %s [-ilp] [-s[0|1]] [-t file] [name(s)]\n\n"
"Options:\n"
" -e Include extension fields in output.\n"
" -i Perform case-insensitive matching.\n"
" -l List all tags.\n"
" -p Perform partial matching.\n"
" -s[0|1|2] Override sort detection of tag file.\n"
" -t file Use specified tag file (default: \"tags\").\n"
"Note that options are acted upon as encountered, so order is significant.\n";
extern int main (int argc, char **argv)
{
int options = 0;
int actionSupplied = 0;
int i;
ProgramName = argv [0];
if (argc == 1)
{
fprintf (stderr, Usage, ProgramName);
exit (1);
}
for (i = 1 ; i < argc ; ++i)
{
const char *const arg = argv [i];
if (arg [0] != '-')
{
findTag (arg, options);
actionSupplied = 1;
}
else
{
size_t j;
for (j = 1 ; arg [j] != '\0' ; ++j)
{
switch (arg [j])
{
case 'e': extensionFields = 1; break;
case 'i': options |= TAG_IGNORECASE; break;
case 'p': options |= TAG_PARTIALMATCH; break;
case 'l': listTags (); actionSupplied = 1; break;
case 't':
if (arg [j+1] != '\0')
{
TagFileName = arg + j + 1;
j += strlen (TagFileName);
}
else if (i + 1 < argc)
TagFileName = argv [++i];
else
{
fprintf (stderr, Usage, ProgramName);
exit (1);
}
break;
case 's':
SortOverride = 1;
++j;
if (arg [j] == '\0')
SortMethod = TAG_SORTED;
else if (strchr ("012", arg[j]) != NULL)
SortMethod = (sortType) (arg[j] - '0');
else
{
fprintf (stderr, Usage, ProgramName);
exit (1);
}
break;
default:
fprintf (stderr, "%s: unknown option: %c\n",
ProgramName, arg[j]);
exit (1);
break;
}
}
}
}
if (! actionSupplied)
{
fprintf (stderr,
"%s: no action specified: specify tag name(s) or -l option\n",
ProgramName);
exit (1);
}
return 0;
}
#endif
/* vi:set tabstop=4 shiftwidth=4: */

View File

@ -0,0 +1,252 @@
/*
* $Id: readtags.h 443 2006-05-30 04:37:13Z darren $
*
* Copyright (c) 1996-2003, Darren Hiebert
*
* This source code is released for the public domain.
*
* This file defines the public interface for looking up tag entries in tag
* files.
*
* The functions defined in this interface are intended to provide tag file
* support to a software tool. The tag lookups provided are sufficiently fast
* enough to permit opening a sorted tag file, searching for a matching tag,
* then closing the tag file each time a tag is looked up (search times are
* on the order of hundreths of a second, even for huge tag files). This is
* the recommended use of this library for most tool applications. Adhering
* to this approach permits a user to regenerate a tag file at will without
* the tool needing to detect and resynchronize with changes to the tag file.
* Even for an unsorted 24MB tag file, tag searches take about one second.
*/
#ifndef READTAGS_H
#define READTAGS_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* MACROS
*/
/* Options for tagsSetSortType() */
typedef enum {
TAG_UNSORTED, TAG_SORTED, TAG_FOLDSORTED
} sortType ;
/* Options for tagsFind() */
#define TAG_FULLMATCH 0x0
#define TAG_PARTIALMATCH 0x1
#define TAG_OBSERVECASE 0x0
#define TAG_IGNORECASE 0x2
/*
* DATA DECLARATIONS
*/
typedef enum { TagFailure = 0, TagSuccess = 1 } tagResult;
struct sTagFile;
typedef struct sTagFile tagFile;
/* This structure contains information about the tag file. */
typedef struct {
struct {
/* was the tag file successfully opened? */
int opened;
/* errno value when 'opened' is false */
int error_number;
} status;
/* information about the structure of the tag file */
struct {
/* format of tag file (1 = original, 2 = extended) */
short format;
/* how is the tag file sorted? */
sortType sort;
} file;
/* information about the program which created this tag file */
struct {
/* name of author of generating program (may be null) */
const char *author;
/* name of program (may be null) */
const char *name;
/* URL of distribution (may be null) */
const char *url;
/* program version (may be null) */
const char *version;
} program;
} tagFileInfo;
/* This structure contains information about an extension field for a tag.
* These exist at the end of the tag in the form "key:value").
*/
typedef struct {
/* the key of the extension field */
const char *key;
/* the value of the extension field (may be an empty string) */
const char *value;
} tagExtensionField;
/* This structure contains information about a specific tag. */
typedef struct {
/* name of tag */
const char *name;
/* path of source file containing definition of tag */
const char *file;
/* address for locating tag in source file */
struct {
/* pattern for locating source line
* (may be NULL if not present) */
const char *pattern;
/* line number in source file of tag definition
* (may be zero if not known) */
unsigned long lineNumber;
} address;
/* kind of tag (may by name, character, or NULL if not known) */
const char *kind;
/* is tag of file-limited scope? */
short fileScope;
/* miscellaneous extension fields */
struct {
/* number of entries in `list' */
unsigned short count;
/* list of key value pairs */
tagExtensionField *list;
} fields;
} tagEntry;
/*
* FUNCTION PROTOTYPES
*/
/*
* This function must be called before calling other functions in this
* library. It is passed the path to the tag file to read and a (possibly
* null) pointer to a structure which, if not null, will be populated with
* information about the tag file. If successful, the function will return a
* handle which must be supplied to other calls to read information from the
* tag file, and info.status.opened will be set to true. If unsuccessful,
* info.status.opened will be set to false and info.status.error_number will
* be set to the errno value representing the system error preventing the tag
* file from being successfully opened.
*/
extern tagFile *tagsOpen (const char *const filePath, tagFileInfo *const info);
/*
* This function allows the client to override the normal automatic detection
* of how a tag file is sorted. Permissible values for `type' are
* TAG_UNSORTED, TAG_SORTED, TAG_FOLDSORTED. Tag files in the new extended
* format contain a key indicating whether or not they are sorted. However,
* tag files in the original format do not contain such a key even when
* sorted, preventing this library from taking advantage of fast binary
* lookups. If the client knows that such an unmarked tag file is indeed
* sorted (or not), it can override the automatic detection. Note that
* incorrect lookup results will result if a tag file is marked as sorted when
* it actually is not. The function will return TagSuccess if called on an
* open tag file or TagFailure if not.
*/
extern tagResult tagsSetSortType (tagFile *const file, const sortType type);
/*
* Reads the first tag in the file, if any. It is passed the handle to an
* opened tag file and a (possibly null) pointer to a structure which, if not
* null, will be populated with information about the first tag file entry.
* The function will return TagSuccess another tag entry is found, or
* TagFailure if not (i.e. it reached end of file).
*/
extern tagResult tagsFirst (tagFile *const file, tagEntry *const entry);
/*
* Step to the next tag in the file, if any. It is passed the handle to an
* opened tag file and a (possibly null) pointer to a structure which, if not
* null, will be populated with information about the next tag file entry. The
* function will return TagSuccess another tag entry is found, or TagFailure
* if not (i.e. it reached end of file). It will always read the first tag in
* the file immediately after calling tagsOpen().
*/
extern tagResult tagsNext (tagFile *const file, tagEntry *const entry);
/*
* Retrieve the value associated with the extension field for a specified key.
* It is passed a pointer to a structure already populated with values by a
* previous call to tagsNext(), tagsFind(), or tagsFindNext(), and a string
* containing the key of the desired extension field. If no such field of the
* specified key exists, the function will return null.
*/
extern const char *tagsField (const tagEntry *const entry, const char *const key);
/*
* Find the first tag matching `name'. The structure pointed to by `entry'
* will be populated with information about the tag file entry. If a tag file
* is sorted using the C locale, a binary search algorithm is used to search
* the tag file, resulting in very fast tag lookups, even in huge tag files.
* Various options controlling the matches can be combined by bit-wise or-ing
* certain values together. The available values are:
*
* TAG_PARTIALMATCH
* Tags whose leading characters match `name' will qualify.
*
* TAG_FULLMATCH
* Only tags whose full lengths match `name' will qualify.
*
* TAG_IGNORECASE
* Matching will be performed in a case-insenstive manner. Note that
* this disables binary searches of the tag file.
*
* TAG_OBSERVECASE
* Matching will be performed in a case-senstive manner. Note that
* this enables binary searches of the tag file.
*
* The function will return TagSuccess if a tag matching the name is found, or
* TagFailure if not.
*/
extern tagResult tagsFind (tagFile *const file, tagEntry *const entry, const char *const name, const int options);
/*
* Find the next tag matching the name and options supplied to the most recent
* call to tagsFind() for the same tag file. The structure pointed to by
* `entry' will be populated with information about the tag file entry. The
* function will return TagSuccess if another tag matching the name is found,
* or TagFailure if not.
*/
extern tagResult tagsFindNext (tagFile *const file, tagEntry *const entry);
/*
* Call tagsTerminate() at completion of reading the tag file, which will
* close the file and free any internal memory allocated. The function will
* return TagFailure is no file is currently open, TagSuccess otherwise.
*/
extern tagResult tagsClose (tagFile *const file);
#ifdef __cplusplus
};
#endif
#endif
/* vi:set tabstop=4 shiftwidth=4: */

View File

@ -0,0 +1,20 @@
#include "include/cef_base.h"
#include "include/cef_v8.h"
namespace v8_extensions {
class Tags : public CefV8Handler {
public:
Tags();
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE;
// Provide the reference counting implementation for this class.
IMPLEMENT_REFCOUNTING(Tags);
};
}

View File

@ -0,0 +1,7 @@
var $tags = {};
(function() {
native function find(path, tag);
$tags.find = find;
})();

View File

@ -0,0 +1,66 @@
#import "tags.h"
#import "readtags.h"
#import <Cocoa/Cocoa.h>
namespace v8_extensions {
Tags::Tags() : CefV8Handler() {
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"v8_extensions/tags.js"];
NSString *extensionCode = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
CefRegisterExtension("v8/tags", [extensionCode UTF8String], this);
}
bool Tags::Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
if (name == "find") {
std::string path = arguments[0]->GetStringValue().ToString();
std::string tag = arguments[1]->GetStringValue().ToString();
tagFileInfo info;
tagFile* tagFile;
tagFile = tagsOpen(path.c_str(), &info);
if (info.status.opened) {
tagEntry entry;
std::vector<CefRefPtr<CefV8Value>> entries;
if (tagsFind(tagFile, &entry, tag.c_str(), TAG_FULLMATCH | TAG_OBSERVECASE) == TagSuccess) {
CefRefPtr<CefV8Value> tagEntry = CefV8Value::CreateObject(NULL);
tagEntry->SetValue("name", CefV8Value::CreateString(entry.name), V8_PROPERTY_ATTRIBUTE_NONE);
tagEntry->SetValue("file", CefV8Value::CreateString(entry.file), V8_PROPERTY_ATTRIBUTE_NONE);
if (entry.kind) {
tagEntry->SetValue("kind", CefV8Value::CreateString(entry.kind), V8_PROPERTY_ATTRIBUTE_NONE);
}
if (entry.address.pattern) {
tagEntry->SetValue("pattern", CefV8Value::CreateString(entry.address.pattern), V8_PROPERTY_ATTRIBUTE_NONE);
}
entries.push_back(tagEntry);
while (tagsFindNext(tagFile, &entry) == TagSuccess) {
tagEntry = CefV8Value::CreateObject(NULL);
tagEntry->SetValue("name", CefV8Value::CreateString(entry.name), V8_PROPERTY_ATTRIBUTE_NONE);
tagEntry->SetValue("file", CefV8Value::CreateString(entry.file), V8_PROPERTY_ATTRIBUTE_NONE);
if (entry.kind) {
tagEntry->SetValue("kind", CefV8Value::CreateString(entry.kind), V8_PROPERTY_ATTRIBUTE_NONE);
}
if (entry.address.pattern) {
tagEntry->SetValue("pattern", CefV8Value::CreateString(entry.address.pattern), V8_PROPERTY_ATTRIBUTE_NONE);
}
entries.push_back(tagEntry);
}
}
retval = CefV8Value::CreateArray(entries.size());
for (int i = 0; i < entries.size(); i++) {
retval->SetValue(i, entries[i]);
}
tagsClose(tagFile);
}
return true;
}
return false;
}
}

View File

@ -137,9 +137,47 @@ describe "Project", ->
waitsForPromise ->
project.getFilePaths().done (foundPaths) -> paths = foundPaths
runs ->
expect(paths).not.toContain('ignored.txt')
describe "ignored file name", ->
ignoredFile = null
beforeEach ->
ignoredFile = fs.join(require.resolve('fixtures/dir'), 'ignored.txt')
fs.write(ignoredFile, "")
afterEach ->
fs.remove(ignoredFile)
it "ignores ignored.txt file", ->
paths = null
project.ignoredNames.push 'ignored.txt'
waitsForPromise ->
project.getFilePaths().done (foundPaths) -> paths = foundPaths
runs ->
expect(paths).not.toContain('ignored.txt')
describe "ignored folder name", ->
ignoredFile = null
beforeEach ->
ignoredFile = fs.join(require.resolve('fixtures/dir'), 'ignored/ignored.txt')
fs.write(ignoredFile, "")
afterEach ->
fs.remove(ignoredFile)
it "ignores ignored folder", ->
paths = null
project.ignoredNames.push 'ignored'
waitsForPromise ->
project.getFilePaths().done (foundPaths) -> paths = foundPaths
runs ->
expect(paths).not.toContain('ignored/ignored.txt')
describe ".scan(options, callback)", ->
describe "when called with a regex", ->
it "calls the callback with all regex matches in all files in the project", ->

View File

@ -35,6 +35,8 @@ describe "SelectList", ->
it "filters the elements in the list based on the scoreElement function and selects the first item", ->
miniEditor.insertText('la')
window.advanceClock(selectList.inputThrottle)
expect(list.find('li').length).toBe 2
expect(list.find('li:contains(Alpha)')).toExist()
expect(list.find('li:contains(Delta)')).toExist()
@ -44,11 +46,15 @@ describe "SelectList", ->
it "displays an error if there are no matches, removes error when there are matches", ->
miniEditor.insertText('nothing will match this')
window.advanceClock(selectList.inputThrottle)
expect(list.find('li').length).toBe 0
expect(selectList.error).not.toBeHidden()
expect(selectList).toHaveClass("error")
miniEditor.setText('la')
window.advanceClock(selectList.inputThrottle)
expect(list.find('li').length).toBe 2
expect(selectList.error).not.toBeVisible()
expect(selectList).not.toHaveClass("error")
@ -109,6 +115,8 @@ describe "SelectList", ->
describe "when there is no item selected (because the list is empty)", ->
it "does not trigger the confirmed hook", ->
miniEditor.insertText("i will never match anything")
window.advanceClock(selectList.inputThrottle)
expect(list.find('li')).not.toExist()
miniEditor.trigger 'core:confirm'
expect(selectList.confirmed).not.toHaveBeenCalled()
@ -124,11 +132,12 @@ describe "SelectList", ->
expect(selectList.confirmed).toHaveBeenCalledWith(array[1])
describe "the core:cancel event", ->
it "triggers the cancelled hook and detaches the select list", ->
it "triggers the cancelled hook and detaches and empties the select list", ->
spyOn(selectList, 'detach')
miniEditor.trigger 'core:cancel'
expect(selectList.cancelled).toHaveBeenCalled()
expect(selectList.detach).toHaveBeenCalled()
expect(selectList.list).toBeEmpty()
describe "when the mini editor loses focus", ->
it "triggers the cancelled hook and detaches the select list", ->
@ -136,4 +145,3 @@ describe "SelectList", ->
miniEditor.trigger 'focusout'
expect(selectList.cancelled).toHaveBeenCalled()
expect(selectList.detach).toHaveBeenCalled()

View File

@ -41,7 +41,7 @@ describe "Selection", ->
expect(selection.isEmpty()).toBeTruthy()
describe "when the cursor precedes the anchor", ->
it "it deletes selected text and clears the selection", ->
it "deletes selected text and clears the selection", ->
selection.cursor.setScreenPosition [0,13]
selection.selectToScreenPosition [0,4]

3
spec/fixtures/tagged-duplicate.js vendored Normal file
View File

@ -0,0 +1,3 @@
function duplicate() {
return false;
}

11
spec/fixtures/tagged.js vendored Normal file
View File

@ -0,0 +1,11 @@
var thisIsCrazy = true;
function callMeMaybe() {
return "here's my number";
}
var iJustMetYou = callMeMaybe();
function duplicate() {
return true;
}

10
spec/fixtures/tags vendored Normal file
View File

@ -0,0 +1,10 @@
!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/
!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/
!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/
!_TAG_PROGRAM_NAME Exuberant Ctags //
!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/
!_TAG_PROGRAM_VERSION 5.8 //
callMeMaybe tagged.js /^function callMeMaybe() {$/;" f
duplicate tagged-duplicate.js /^function duplicate() {$/;" f
duplicate tagged.js /^function duplicate() {$/;" f
thisIsCrazy tagged.js /^var thisIsCrazy = true;$/;" v

View File

@ -2,4 +2,3 @@ window.keymap.bindKeys ".select-list .mini.editor input",
'enter': 'core:confirm',
'escape': 'core:cancel'
'meta-w': 'core:cancel'

View File

@ -52,20 +52,14 @@ class Project
getFilePaths: ->
deferred = $.Deferred()
fs.getAllPathsAsync @getPath(), (paths) =>
fs.getAllFilePathsAsync @getPath(), (paths) =>
paths = paths.filter (path) => not @isPathIgnored(path)
deferred.resolve(paths)
deferred.promise()
isPathIgnored: (path) ->
lastSlash = path.lastIndexOf('/')
if lastSlash isnt -1
name = path.substring(lastSlash + 1)
else
name = path
for ignored in @ignoredNames
return true if name is ignored
for segment in path.split("/")
return true if _.contains(@ignoredNames, segment)
@ignoreRepositoryPath(path)

View File

@ -15,13 +15,15 @@ class SelectList extends View
@viewClass: -> 'select-list'
maxItems: Infinity
scheduleTimeout: null
inputThrottle: 200
filteredArray: null
cancelling: false
initialize: ->
requireStylesheet 'select-list.css'
@miniEditor.getBuffer().on 'change', => @populateList()
@miniEditor.getBuffer().on 'change', => @schedulePopulateList()
@miniEditor.on 'focusout', => @cancel() unless @cancelling
@on 'core:move-up', => @selectPreviousItem()
@on 'core:move-down', => @selectNextItem()
@ -36,6 +38,10 @@ class SelectList extends View
@confirmSelection() if $(e.target).closest('li').hasClass('selected')
e.preventDefault()
schedulePopulateList: ->
clearTimeout(@scheduleTimeout)
@scheduleTimeout = setTimeout((=> @populateList()), @inputThrottle)
setArray: (@array) ->
@populateList()
@selectItem(@list.find('li:first'))
@ -43,12 +49,11 @@ class SelectList extends View
setError: (message) ->
if not message or message.length == ""
@error.text("")
@error.hide()
@error.text("").hide()
@removeClass("error")
else
@error.text(message)
@error.show()
@setLoading()
@error.text(message).show()
@addClass("error")
setLoading: (message) ->
@ -113,8 +118,9 @@ class SelectList extends View
@confirmed(element) if element?
cancel: ->
@list.empty()
@cancelling = true
@cancelled()
@detach()
@cancelling = false
clearTimeout(@scheduleTimeout)

View File

@ -20,7 +20,9 @@ class EventPalette extends SelectList
keyBindings: null
initialize: (@rootView) ->
@command 'event-palette:toggle', => @cancel()
@command 'event-palette:toggle', =>
@cancel()
false
super
attach: ->

View File

@ -189,3 +189,23 @@ describe 'FuzzyFinder', ->
expect(finder.hasParent()).toBeFalsy()
expect(activeEditor.isFocused).toBeTruthy()
expect(finder.miniEditor.isFocused).toBeFalsy()
describe "cached file paths", ->
it "caches file paths after first time", ->
spyOn(rootView.project, "getFilePaths").andCallThrough()
rootView.trigger 'fuzzy-finder:toggle-file-finder'
waitsFor ->
finder.list.children('li').length > 0
runs ->
expect(rootView.project.getFilePaths).toHaveBeenCalled()
rootView.project.getFilePaths.reset()
rootView.trigger 'fuzzy-finder:toggle-file-finder'
rootView.trigger 'fuzzy-finder:toggle-file-finder'
waitsFor ->
finder.list.children('li').length > 0
runs ->
expect(rootView.project.getFilePaths).not.toHaveBeenCalled()

View File

@ -1,6 +1,7 @@
{View, $$} = require 'space-pen'
SelectList = require 'select-list'
_ = require 'underscore'
$ = require 'jquery'
Editor = require 'editor'
module.exports =
@ -20,6 +21,7 @@ class FuzzyFinder extends SelectList
initialize: (@rootView) ->
super
$(window).on 'focus', => @array = null
itemForElement: (path) ->
$$ -> @li path
@ -51,9 +53,12 @@ class FuzzyFinder extends SelectList
@attach() if @paths?.length
populateProjectPaths: ->
@setLoading("Indexing...")
@rootView.project.getFilePaths().done (paths) =>
@setArray(paths)
if @array?.length > 0
@setArray(@array)
else
@setLoading("Indexing...")
@rootView.project.getFilePaths().done (paths) =>
@setArray(paths)
populateOpenBufferPaths: ->
@paths = @rootView.getOpenBufferPaths().map (path) =>

View File

@ -3,28 +3,31 @@ OutlineView = require 'outline-view'
TagGenerator = require 'outline-view/src/tag-generator'
describe "OutlineView", ->
[rootView, outlineView] = []
[rootView, outlineView, setArraySpy] = []
beforeEach ->
rootView = new RootView(require.resolve('fixtures'))
rootView.activateExtension(OutlineView)
outlineView = OutlineView.instance
rootView.attachToDom()
setArraySpy = spyOn(outlineView, 'setArray').andCallThrough()
afterEach ->
rootView.deactivate()
setArraySpy.reset()
describe "when tags can be generated for a file", ->
it "initially displays all JavaScript functions with line numbers", ->
rootView.open('sample.js')
expect(rootView.find('.outline-view')).not.toExist()
attachSpy = spyOn(outlineView, 'attach').andCallThrough()
rootView.getActiveEditor().trigger "outline-view:toggle"
expect(outlineView.find('.loading')).toHaveText 'Generating symbols...'
waitsFor ->
attachSpy.callCount > 0
setArraySpy.callCount > 0
runs ->
expect(outlineView.find('.loading')).toBeEmpty()
expect(rootView.find('.outline-view')).toExist()
expect(outlineView.list.children('li').length).toBe 2
expect(outlineView.list.children('li:first').find('.function-name')).toHaveText 'quicksort'
@ -37,14 +40,15 @@ describe "OutlineView", ->
it "displays error when no tags match text in mini-editor", ->
rootView.open('sample.js')
expect(rootView.find('.outline-view')).not.toExist()
attachSpy = spyOn(outlineView, 'attach').andCallThrough()
rootView.getActiveEditor().trigger "outline-view:toggle"
waitsFor ->
attachSpy.callCount > 0
setArraySpy.callCount > 0
runs ->
outlineView.miniEditor.setText("nothing will match this")
window.advanceClock(outlineView.inputThrottle)
expect(rootView.find('.outline-view')).toExist()
expect(outlineView.list.children('li').length).toBe 0
expect(outlineView.error).toBeVisible()
@ -53,6 +57,8 @@ describe "OutlineView", ->
# Should remove error
outlineView.miniEditor.setText("")
window.advanceClock(outlineView.inputThrottle)
expect(outlineView.list.children('li').length).toBe 2
expect(outlineView).not.toHaveClass "error"
expect(outlineView.error).not.toBeVisible()
@ -61,11 +67,11 @@ describe "OutlineView", ->
it "shows an error message when no matching tags are found", ->
rootView.open('sample.txt')
expect(rootView.find('.outline-view')).not.toExist()
attachSpy = spyOn(outlineView, 'attach').andCallThrough()
rootView.getActiveEditor().trigger "outline-view:toggle"
setErrorSpy = spyOn(outlineView, "setError").andCallThrough()
waitsFor ->
attachSpy.callCount > 0
setErrorSpy.callCount > 0
runs ->
expect(rootView.find('.outline-view')).toExist()
@ -73,6 +79,7 @@ describe "OutlineView", ->
expect(outlineView.error).toBeVisible()
expect(outlineView.error.text().length).toBeGreaterThan 0
expect(outlineView).toHaveClass "error"
expect(outlineView.find('.loading')).not.toBeVisible()
it "moves the cursor to the selected function", ->
tags = []
@ -92,7 +99,7 @@ describe "OutlineView", ->
outlineView.attach()
expect(rootView.find('.outline-view')).toExist()
outlineView.confirmed(tags[1])
expect(rootView.getActiveEditor().getCursorBufferPosition()).toEqual [1,0]
expect(rootView.getActiveEditor().getCursorBufferPosition()).toEqual [1,2]
describe "TagGenerator", ->
it "generates tags for all JavaScript functions", ->
@ -118,3 +125,29 @@ describe "OutlineView", ->
generator = new TagGenerator(path, callback)
generator.generate().done ->
expect(tags.length).toBe 0
describe "jump to declaration", ->
it "doesn't move the cursor when no declaration is found", ->
rootView.open("tagged.js")
editor = rootView.getActiveEditor()
editor.setCursorBufferPosition([0,2])
editor.trigger 'outline-view:jump-to-declaration'
expect(editor.getCursorBufferPosition()).toEqual [0,2]
it "moves the cursor to the declaration", ->
rootView.open("tagged.js")
editor = rootView.getActiveEditor()
editor.setCursorBufferPosition([6,24])
editor.trigger 'outline-view:jump-to-declaration'
expect(editor.getCursorBufferPosition()).toEqual [2,0]
it "displays matches when more than one exists and opens the selected match", ->
rootView.open("tagged.js")
editor = rootView.getActiveEditor()
editor.setCursorBufferPosition([8,14])
editor.trigger 'outline-view:jump-to-declaration'
expect(outlineView.list.children('li').length).toBe 2
expect(outlineView).toBeVisible()
outlineView.confirmed(outlineView.array[0])
expect(rootView.getActiveEditor().getPath()).toBe rootView.project.resolve("tagged-duplicate.js")
expect(rootView.getActiveEditor().getCursorBufferPosition()).toEqual [0,4]

View File

@ -1,2 +1,3 @@
window.keymap.bindKeys '.editor'
'meta-j': 'outline-view:toggle'
'meta-.': 'outline-view:jump-to-declaration'

View File

@ -2,6 +2,10 @@
SelectList = require 'select-list'
Editor = require 'editor'
TagGenerator = require 'outline-view/src/tag-generator'
TagReader = require 'outline-view/src/tag-reader'
Point = require 'point'
fs = require 'fs'
$ = require 'jquery'
module.exports =
class OutlineView extends SelectList
@ -11,6 +15,7 @@ class OutlineView extends SelectList
requireStylesheet 'outline-view/src/outline-view.css'
@instance = new OutlineView(rootView)
rootView.command 'outline-view:toggle', => @instance.toggle()
rootView.command 'outline-view:jump-to-declaration', => @instance.jumpToDeclaration()
@viewClass: -> "#{super} outline-view"
@ -32,11 +37,13 @@ class OutlineView extends SelectList
@cancel()
else
@populate()
@attach()
populate: ->
tags = []
callback = (tag) -> tags.push tag
path = @rootView.getActiveEditor().getPath()
@setLoading("Generating symbols...")
new TagGenerator(path, callback).generate().done =>
if tags.length > 0
@miniEditor.show()
@ -46,13 +53,19 @@ class OutlineView extends SelectList
@setError("No symbols found")
setTimeout (=> @detach()), 2000
@attach()
confirmed : ({position, name}) ->
confirmed : (tag) ->
@cancel()
@openTag(tag)
openTag: ({position, file}) ->
@rootView.openInExistingEditor(file, true, true) if file
@moveToPosition(position)
moveToPosition: (position) ->
editor = @rootView.getActiveEditor()
editor.scrollToBufferPosition(position, center: true)
editor.setCursorBufferPosition(position)
editor.moveCursorToFirstCharacterOfLine()
cancelled: ->
@miniEditor.setText('')
@ -61,3 +74,30 @@ class OutlineView extends SelectList
attach: ->
@rootView.append(this)
@miniEditor.focus()
getTagLine: (tag) ->
pattern = $.trim(tag.pattern?.replace(/(^^\/\^)|(\$\/$)/g, '')) # Remove leading /^ and trailing $/
return unless pattern
for line, index in fs.read(@rootView.project.resolve(tag.file)).split('\n')
return new Point(index, 0) if pattern is $.trim(line)
jumpToDeclaration: ->
editor = @rootView.getActiveEditor()
matches = TagReader.find(editor)
return unless matches.length
if matches.length is 1
position = @getTagLine(matches[0])
@openTag(file: matches[0].file, position: position) if position
else
tags = []
for match in matches
position = @getTagLine(match)
continue unless position
tags.push
file: match.file
name: fs.base(match.file)
position: position
@miniEditor.show()
@setArray(tags)
@attach()

View File

@ -31,8 +31,5 @@
color: #ddd;
-webkit-border-radius: 3px;
padding: 0 4px;
}
.outline-view ol .function-line {
background: rgba(0, 0, 0, .2);
}

View File

@ -0,0 +1,13 @@
fs = require 'fs'
module.exports =
find: (editor) ->
word = editor.getTextInRange(editor.getCursor().getCurrentWordBufferRange())
return [] unless word.length > 0
project = editor.rootView().project
tagsFile = project.resolve("tags") or project.resolve("TAGS")
return [] unless fs.isFile(tagsFile)
$tags.find(tagsFile, word) or []

View File

@ -31,6 +31,7 @@ class WrapGuide extends View
@updateGuide(@editor)
@editor.on 'editor-path-change', => @updateGuide(@editor)
config.on 'update', => @setFontSize(config.editor.fontSize)
@editor.on 'before-remove', => @rootView.off('.wrap-guide')
setFontSize: (fontSize) ->
return if fontSize == @fontSize

View File

@ -112,8 +112,8 @@ module.exports =
@makeTree(@directory(path))
@makeDirectory(path)
getAllPathsAsync: (rootPath, callback) ->
$native.getAllPathsAsync(rootPath, callback)
getAllFilePathsAsync: (rootPath, callback) ->
$native.getAllFilePathsAsync(rootPath, callback)
traverseTree: (rootPath, onFile, onDirectory) ->
$native.traverseTree(rootPath, onFile, onDirectory)