Code covered by the BSD License  

Highlights from
Command window file explorer

image thumbnail

Command window file explorer

by

 

09 Feb 2011 (Updated )

Embedded html links to open, run, or edit files from the command window. With bookmarks!

explore.m
% EXPLORE  Displays a directory explorer with html embedded links within
%    the Command Window. Click on the underlined links to change the current
%    directory. Add bookmarks to the top layer by clicking on a "_" while
%    you are in the directory you want to bookmark.
%    Click on a '' after any .m file to run it as a script
%    Click on the '#' after any other type of file to open it using the
%    default system program. ex: bookmarks.txt would open with notepad under
%    windows.
%    Adding a bookmark may be done manually with:
%    >> explore('add',cd,bookmark_number);  % where bookmark_number is an
%      integer between 1 and 40.

function explore(varargin)
home   %scrolls the command window to the move everything up
if nargin == 3  %add a new bookmark
  if strcmp(varargin{1},'add')
    addbm(varargin{2},varargin{3}); %directory, line number
  end
end
dispbookmarks();   %displays the bookmarks toolbar on the first line
dispcd();          %displays the contents of the current folder
end

%% Display bookmarks
function dispbookmarks()
% displays a line of '#'s each with a different link.
% the blank links contain 'matlab:addlink(cd,n)' where n is the number
% of the link, and cd is the current directory.
% this works by loading a text file where each line contains a directory.
% the position of the link on the toolbar depends on the line number in the file.

%% process the file
% find the explore directory -- needed to open the bookmarks.txt file
exd = which('explore');
a=strfind(exd,'\');
exd = exd(1:a(end));  % c:\explore.m  ->   c:\

% load or create the file
fid = fopen([exd, 'bookmarks.txt'],'r');  %open for reading
frewind(fid); %move to the beginning of the file

try
  bookmarklinks{40} = []; %make room for 40 links
  bookmark = fgetl(fid); %get one line from the file
  m = 1;
  while ischar(bookmark)
    if ~isempty(bookmark)  % not ''
      bookmarklinks{m} = bookmark;  %add the directory to the list
    else
      bookmarklinks{m} = [];  %add an empty marker to the list
    end
    bookmark = fgetl(fid);
    m=m+1;
    if m > 40  %any more than 40 bookmarks won't fit in an 80 width space
      bookmark = -1;
    end
  end
  fclose(fid);
catch %#ok<*CTCH>
  fclose(fid);
end



%% display the bookmarks
for m = 1:40
  if isempty(bookmarklinks{m}) %empty bookmark
    blink = ['<a href="matlab:explore(''add'',''',slashpad(cd),''',',num2str(m),');"></a>'];
    fprintf(2,blink)
  else
    %load the bookmark
    bm = bookmarklinks{m};
    % bookmarks have a letter and a space before link
    tag = bm(1);
    bm = bm(3:end);
    blink = ['<a href="matlab:expcd(''',slashpad(bm),''');">',tag,'</a>'];
    % link to change the directory and re-print the explore screen.
    fprintf(blink)
  end
  
  %display another space if the line number is < 80
  if m < 40
    fprintf('.');
  else
    %new line
    fprintf('\n');
  end
  
end
end
%% Add a bookmark
function addbm(newdir,linenum)
% adds the directory(d) to bookmarks.txt at linenum (line number)

% find the explore directory -- needed to open the bookmarks.txt file
exd = which('explore');
a=strfind(exd,'\');
exd = exd(1:a(end));  % c:\explore.m  ->   c:\

% load or create the file
fid = fopen([exd, 'bookmarks.txt'],'r');  %open for reading
frewind(fid); %move to the beginning of the file
%% read the file, before adding a line
try
  bookmarklinks{40} = []; %make room for 40 links
  bookmark = fgetl(fid); %get one line from the file
  m = 1;
  while ischar(bookmark)
    if ~isempty(bookmark)  % not ''
      bookmarklinks{m} = bookmark;  %add the directory to the list
    else
      bookmarklinks{m} = [];  %add an empty marker to the list
    end
    bookmark = fgetl(fid);
    m=m+1;
    if m > 40  %any more than 40 bookmarks won't fit in an 80 width space
      bookmark = -1;
    end
  end
  fclose(fid);
catch
  fclose(fid);
  error('??? EXPLORE  -- Unable to load bookmarks.txt')
end
%% add the new directory to the cell, then write the whole thing

% find the token from the first letter of the highest directory name
a = strfind(newdir,'\');

key = upper(newdir(a(end)+1));  % 'G; from c:\matlab\goto\
bookmarklinks{linenum} = [key,' ',newdir];
try
  fid = fopen([exd, 'bookmarks.txt'],'w+');  %discard and open for writing
  for i = 1:40
    
    if ~isempty(bookmarklinks{i})
      %disp(bookmarklinks{i})
      fwrite(fid,bookmarklinks{i},'char*1');
      fprintf(fid,'\n');
    else
      fprintf(fid,'\n');
    end
  end
  fclose(fid);
catch e
  fclose(fid);
  disp(e)
end
end
%% Display current directory contents
function dispcd()
%displays current directory contents with links to files and directories

x = sortdir;
files = {x.name};             %file or directory names in a cell
isdir = [x.isdir];            %logical array of directories
num   = numel(x);             %number of files
rows  = ceil(num/4);          % 4 columns,
len   = longestcell(files)+3; %longest length of all strings in a cell
pad   = fix((80-(len*4))/4);  %spaces to pad between columns
cols  = 4;
if (pad < 3)  %draw 3 columns instead of 4
  rows  = ceil(num/3);
  len   = longestcell(files)+3;
  pad   = fix((80-(len*3))/3);
  cols  = 3;
end

%start drawing
fnum = 1;  %current file number
for row = 1:rows
  for col = 1:cols
    try %#ok<*TRYNC>
      if col > 1
        fprintf(repmat(' ',1,pad)); %pad with spaces
      end
      f = files{fnum};  %filename with extension
      if isdir(fnum)  %change directory
        fpad = repmat(' ',1,len-numel(f)-3);
        str = ['<a href="matlab:expcd(''',files{fnum},''')">',f,'</a>'];
        % display a '&' as a link to open this directory in explorer
        if ~strcmp(f(1),'.')  %can't fprintf 'c:\matlab\..'
          funstr = ['<a href="matlab:system([''explorer ',slashpad(cd),'\',f(1:end),'\\'']);">&</a>'];
          fpad = [' ',funstr,fpad(1:end)];
        else
          fpad = ['  ',fpad];
        end
        fprintf(str); %print the link
        fprintf(2,fpad); %pad the string with spaces so all cols line up
      else  %edit the file
        fpad = repmat(' ',1,len-numel(f)-1);
        str = ['<a href="matlab:edit(''',files{fnum},''')">',f,'</a>'];
        if strcmp(f(end-1:end),'.m')
          % display an '' as a link to run this file as a script
          funstr = ['<a href="matlab:',f(1:end-2),'()"></a>'];
          fpad = [' ',funstr,fpad(1:end-2)];
          % 'filename.m'  to 'filename()'
          fprintf(2,str); %print the link
          fprintf(fpad); %pad the string with spaces so all cols line up
        else
          % display an '#' as a link to open this file with the default program
          funstr = ['<a href="matlab:system(''',f(1:end),''')">#</a>'];
          fpad = [' ',funstr,fpad(1:end-2)];
          % 'filename.txt'  to  'system('filename.txt')'
          fprintf(str); %print the link
          fprintf(2,fpad); %pad the string with spaces so all cols line up
        end
      end
      fnum = fnum+1;  %Next file!
    end
  end
  fprintf('\n');
end
end

%% find the longest filename
function x = longestcell(y)
% finds the length of the longest string in a cell of strings
x=0;
for i = 1:numel(y)
  if numel(y{i}) > x;
    x=numel(y{i});
  end
end
end
%% double slashes -- 'bla\h' to 'bla\\h'
function x = slashpad(s)
% SLASHPAD  Function to double '\'s in strings. Useful for calling fprintf
%   with slashpad(cd). ex: 'c:\matlab'  -> 'c:\\matlab'
sls = '\';
a = strfind(s,sls);
if numel(a) > 0
  x = [s(1:a(1)),sls];
  for i = 2:numel(a)
    if s(a(i)-1) ~= s(a(i))
      x = [x, s(a(i-1)+1:a(i)),sls]; %#ok<*AGROW>
    else
      x = [x, s(a(i-1)+1:a(i))];
    end
  end
  x = [x,s(a(end)+1:end),sls];
else
  x = s;
end
end
%% return a sorted directory listing
% SORTDIR  returns a sorted directory listing.
%   x = sortdir  is the same as x = sortdir(cd)
function x = sortdir(d)
% if no directory is given, use the current directory
if nargin == 0
  d = cd;
end
[a xdir]  = system(['dir ',d,'/AD /B']);  %brief directory listing (no files)
[a xfile] = system(['dir ',d,'/A-D /B']); %brief file listing

x = str2struct(xdir,xfile);
end
%% two strings to a directory struct
function x = str2struct(d,f)
%return an abreviated directory structure
%x.isdir   --logical
%x.name    --char array
if strcmp(f,['File Not Found',10])
  % 'File Not Found' isn't a directory...
  f = '';
end
%there is a char(10) after each file/directory, including the last
ad = [0 strfind(d,10)];
af = [0 strfind(f,10)];

%init x
% ad and af both have an extra name, but we're adding just one, so ... -1
x(numel(ad)+numel(af)-1).name = '';

% windows "dir" does not include '..', so add it
x(1).name = '..';
x(1).isdir = true;
%fill in directories
if numel(ad) > 1
  for m = 2:numel(ad)
    x(m).name = d(ad(m-1)+1:ad(m)-1);
    x(m).isdir = true;
  end
else
  m=1;
end
%fill in files
if numel(af) > 1
  for n = 2:numel(af)
    x(n+m-1).name = f(af(n-1)+1:af(n)-1);
    x(n+m-1).isdir = false;
  end
else
end
end

Contact us