Code: Select all
/*****************************************************************************
Insert specified text at the current cursor position in the file being edited
******************************************************************************/
implement main
open core
clauses
run():-
console::init(),
/*
Retrieve the command line*/
CmdLine = mainexe::getCommandLine(),
/*
Retrive the 3 inout arguments: file, line, column and text. They are comma separated*/
Args = string::split_delimiter(CmdLine, ","),
/*
There must be 4 arguments.*/
Args == [Filename, Linestr, Colstr, Text],
/*
The line and column are integers*/
Line = toterm(Linestr),
Col = toterm(Colstr),
/*
Retrieve the text from the file*/
Instr = file::readString(Filename),
/*
Find the cursor position in the text, starting from line 1 and initial position 0. If the
$(position) attribute was available this line and its associated coding would have been not
be necessary.*/
find_position(1, Line, Col, Instr, 0)=Position,
/*
Split the input text at the requested poistion*/
string::front(Instr, Position, Part1, Part2),
/*
Insert the requested text*/
OutStr = string::concat(Part1, Text, Part2),
/*
Save the output back to the original source file*/
file::writeString(Filename, OutStr).
/*
Returns the position of a requested location (in terms of line and column position) in the given
string*/
class predicates
find_position:(integer LineCurrent, integer LineTarget, integer Col, string Text, charCount PositionIn)->charCount PositionOut.
clauses
/*
We have reached the requested line, stop the search and return the requested position*/
find_position(Line, Line, Col, _Text, PositionIn)=PositionOut:-!,
/*
I'm not sure why I have to subtract 1 to get the correct results*/
PositionOut = PositionIn+Col-1.
find_position(Line, LineRef, Col, Text, PositionIn)=PositionOut:-
/*
Search for the new line separator*/
string::search(Text, "\n") =CharCount,!,
/*
If found, split the text at that position; discard the front (inlcuding the new line marker)
and continue searching using the remaining text*/
string::front(Text, CharCount+1, _Text1, Text2),
/*
Update the character count position*/
Position2 = PositionIn + CharCount+1,
/*
Continue the search. Remember to increase the line counter*/
find_position(Line+1, LineRef, Col, Text2, Position2)=PositionOut.
find_position(_Line, _LineRef, _Col, _Text, _PositionIn)=_:-
exception::raise_error("Position not found").
end implement main
goal
mainExe::run(main::run).