Jump to content

AutoMathEdit


czardas
 Share

Recommended Posts

AutoMathEdit

This is a very simple language written in AutoIt. AutoMathEdit only handles numeric operations and lacks the fexibility and functionality of other programming languages. it's still a language nonetheless! See this post:

There are currently no keywords or loops, but the intended purpose of AutoMathEdit is to replace the calculator for quick tasks. The standard windows calculator does not keep tabs on every number you type. This is one advantage of using AutoMathEdit instead of using a standard calculator.

This is the first scripting language I have ever written and it was certainly an education. I know I'm only scratching the surface with this, but everyone has to start soimewhere. I have gained much respect for the dev team after this endeavour. Dealing with so many complicated commands must be a nightmare.

AutoMathEdit is meant to be used exclusivey within an Edit control. The function Echo behaves like the AutoIt function ConsoleWrite. This is an alpha release and there are still several bugs need ironing out.

AutoMathEdit.au3

#include-once

#include <Math.au3>
#include <Array.au3>

; #INDEX# =======================================================================================================================
; Title .........: AutoMathEdit Version 0.0.0.6 (Alpha)
; AutoIt Version : 3.3.8.1
; Language ......: English
; Description ...: Simple (maths only) scripting language based on AutoIt
; Notes .........: AutoMathEdit makes use of AutoIt syntax and standard maths functions.
;          The library is not yet complete and this release is for evaluation purposes.
;+
;          Supported AutoIt functions:- Abs ACos ASin ATan BitAND BitNOT BitOR BitRotate
;          BitShift BitXOR Cos Ceiling Dec Exp Floor Hex Log Mod Random Round Sin Sqrt
;+
;          Supported UDF functions:- _ATan2 _Combinations _Degree Echo _Factorial _Max _Min
;          _Radian _Permutations
;+
;          Supported variable types:- integers floats binary
;+
;          Supported operators:- + - * / ^ = += -= *= /=
;+
;          Constants:-
;          $MATH_E .... (Napiers Constant)
;          $MATH_PHI .. (Golden Ratio)
;          $MATH_PI ... (Pi)
;          $MATH_PSI .. (Reciprocal Fibonacci Constant)
;+
;          Supported syntax:-
;          1. End of line comments (semicolon)
;          2. Line continuation (underscore)
;+
;          General Comments:
;          UDF functions are included automatically.
;          All variables are declared automatically.
;          The use of $ (dollar sign) for variable names is optional.
;          The function Echo returns the value of an expression.
;          Echo(expression) ;= value
;+
;          Thanks to the following devs and members who's examples have been a great inspiration:
;          Jon, Manadar, Mat, Valik, trancexx, UEZ (list is not complete)
;+
; Author(s) .....: Nick Wilkinson (czardas)
; ===============================================================================================================================


; #CURRENT# =====================================================================================================================
;_Combinations
;_Execute
;_Factorial
;_Permutations
; ===============================================================================================================================


; #INTERNAL_USE_ONLY#============================================================================================================
;__AssignSplit
;__ErrorMsg
;__GetBreakPoint
;__GetNewStr
;__GetSubArr
;__IsConst
;__IsFunc
;__IsReserved
;__Return
;__StripOutStrings
; ===============================================================================================================================


; #FUNCTION# ====================================================================================================================
; Name...........: _Execute
; Description ...: Runs AutoMathEdit
; Syntax.........: _Execute($_sScript_)
; Parameters ....: $_sScript_ .... The string to parse.
; Return values .: Success ....... Parses AutoMathEdit and returns the new code string.
;          Failure ....... Parses AutoMathEdit up to the fail point and sets @error
;          |@error = 1 ... Illegal characters
;          |@error = 2 ... Invalid Syntax
;          |@error = 3 ... Function not recognised
;          |@error = 4 ... Unexpected Termination
;          |@error = 5 ... Unterminated String
;          |@error = 6 ... Failed to reassign mathematical constant
;          |@error = 7 ... Missing Parentheses
;          |@error = 8 ... Unassigned Variable
; Author ........: czardas
; Modified.......:
; Remarks .......: _Execute also handles calls to the Echo() function which evaluates an expression.
;          The value returned by the function Echo appears as a comment in the returned code.
; Related .......: None
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================

Func _Execute($_sScript_)
    If Not StringLen($_sScript_) Then Return SetError(4, 0, $_sScript_)

    Local Const $MATH_E = 2.71828182845904523536028747135266249 ; Napiers Constant
    Local Const $MATH_PHI = 1.61803398874989484820458683436563811772 ; Golden Ratio
    Local Const $MATH_PI = 3.14159265358979323846264338328 ; Pi
    Local Const $MATH_PSI = 3.359885666243177553172011302918927179688905133731 ; Reciprocal Fibonacci constant

    Local $_aRawData_ = StringSplit(StringStripCR($_sScript_), @LF)
    $_sScript_ = StringRegExpReplace($_sScript_, "(;.*)", "") ; Remove comments

    Local $_subStr_ ; Substitute string for $ and to avoid conflicts with reserved variables or constants
    __GetNewStr($_sScript_, $_subStr_)

    Local $_aTemp_, $_error_, $_sFail_ = "" ; To store the string which could not be parsed
    $_aTemp_ = __GetSubArr($_sScript_, $_subStr_, $_sFail_) ; Returns an array of substitute patterns
    $_error_ = @error

    Local $_aScriptArr_, $foo, $_sRawCode_ = $_sScript_ ; Keep original code intact
    $_sScript_ = StringReplace($_sScript_, "$MATH", ";") ; To avoid corrupting constant variable names
    $_sScript_ = StringReplace($_sScript_, "$", $_subStr_) ; To avoid conflicts with duplicate variable names
    $_sScript_ = StringReplace($_sScript_, ";", "$MATH") ; Replace the correct math constant names

    If $_error_ = 0 Then
        For $foo = 1 To $_aTemp_[0][0]
            $_sScript_ = StringRegExpReplace($_sScript_, "(?i)(b" & $_aTemp_[$foo][0] & "b)", $_aTemp_[$foo][1])
        Next
    Else
        If StringLen($_sFail_) Then
            $_aScriptArr_ = StringSplit(StringStripCR($_sScript_), @LF) ; Split to lines of raw code
            For $foo = 0 To UBound($_aScriptArr_) -1
                If StringInStr($_aScriptArr_[$foo], $_sFail_) Then
                    $_sFail_ = "Line " & $foo & @LF & $_sFail_
                    ExitLoop
                EndIf
            Next
            MsgBox(16, "Error", __ErrorMsg($_error_) & @LF & $_sFail_)
            Return SetError($_error_, 0, __Return($_aRawData_)) ; Unable to parse - Errors vary
        EndIf
    EndIf

    Local $bar ; Variable integer
    $_aScriptArr_ = StringSplit(StringStripCR($_sScript_), @LF) ; Split to lines of raw code

    For $foo = 1 To $_aScriptArr_[0]
        $bar = $foo
        While StringRegExp($_aScriptArr_[$foo], "(s_s*z)") ; Check for line continuation underscore NOT CHECKED
            If $bar < $_aScriptArr_[0] Then

                If StringLen($_aScriptArr_[$bar +1]) Then
                    $_aScriptArr_[$foo] = StringRegExpReplace($_aScriptArr_[$foo], "(s_s*z)", " " & $_aScriptArr_[$bar +1])
                    $_aScriptArr_[$bar +1] = ""
                    $bar += 1
                Else
                    MsgBox(16, "Error", "Line " & $bar & @LF & __ErrorMsg(5) & @LF & $_aRawData_[$bar])
                    Return SetError(5, 0, __Return($_aRawData_)) ; Unterminated String
                EndIf

            ElseIf StringRegExp($_aScriptArr_[$foo], "(s_s*z)") Then
                MsgBox(16, "Error", "Line " & $_aScriptArr_[0] & @LF & __ErrorMsg(5))
                Return SetError(5, 0, __Return($_aRawData_)) ; Unterminated String
            EndIf
        WEnd
        $foo = $bar
    Next

    For $foo = 1 To $_aScriptArr_[0] ; Parse each line sequence
        $_aScriptArr_[$foo] = StringStripWS($_aScriptArr_[$foo], 3)
        If Not StringLen($_aScriptArr_[$foo]) Then ContinueLoop

        If StringInStr($_aScriptArr_[$foo], "=") Then
            $_aAssign_ = __AssignSplit($_aScriptArr_[$foo])
            $_error_ = @error

            If $_error_ = 0 Then
                If StringLeft($_aAssign_[1], 1) = "$" Then
                    $_aAssign_[1] = StringTrimLeft($_aAssign_[1], 1)
                Else
                    MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo])
                    Return SetError(2, 0, __Return($_aRawData_))
                EndIf

                If __IsConst($_aAssign_[1]) Then
                    MsgBox(16, "Error", __ErrorMsg(6) & @LF & "Line " & $foo & @LF & "$" & $_aAssign_[1] & " =")
                    Return SetError(6, 0, __Return($_aRawData_))
                EndIf

                $_aAssign_[2] = Execute($_aAssign_[2])
                $_error_ = @error
                If StringLen($_aAssign_[2]) = 0 Or ($_aAssign_[2] <> 0 And $_error_ <> 0 And Not IsNumber(Number($_aAssign_[2])) Or $_aAssign_[2] = False) Then
                    MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aAssign_[1] & " =")
                    Return SetError(2, 0, __Return($_aRawData_))
                EndIf

                If $_aAssign_[0] = 2 Then
                    Assign($_aAssign_[1], $_aAssign_[2])

                ElseIf IsDeclared($_aAssign_[1]) Then
                    $_nValue_ = Execute("$" & $_aAssign_[1])

                    Switch $_aAssign_[0]
                        Case "+"
                            Assign($_aAssign_[1], $_nValue_ + $_aAssign_[2])
                        Case "-"
                            Assign($_aAssign_[1], $_nValue_ - $_aAssign_[2])
                        Case "*"
                            Assign($_aAssign_[1], $_nValue_ * $_aAssign_[2])
                        Case "/"
                            Assign($_aAssign_[1], $_nValue_ / $_aAssign_[2])
                    EndSwitch

                Else
                    MsgBox(16, "Error", __ErrorMsg(8) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo])
                    Return SetError(8, 0, __Return($_aRawData_))
                EndIf
            Else
                $bar = __GetBreakPoint($_sRawCode_, $foo, "=", 2)
                MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $bar & @LF & "=")
                Return SetError(2, 0, __Return($_aRawData_))
            EndIf

        ; Echo is an internal command which writes the value of an expression.
        ElseIf StringLeft($_aScriptArr_[$foo], 4) = "Echo" Then
            $_aScriptArr_[$foo] = StringStripWS(StringTrimLeft($_aScriptArr_[$foo], 4), 3)

            If StringLeft($_aScriptArr_[$foo], 1) <> "(" Then
                MsgBox(16, "Error", __ErrorMsg(7) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo])
                Return SetError(7, 0, __Return($_aRawData_)) ; Missing Parentheses
            EndIf

            $bar = __GetBreakPoint($_sRawCode_, $foo)
            If StringRight($_aScriptArr_[$foo], 1) <> ")" Then
                MsgBox(16, "Error", __ErrorMsg(7) & @LF & "Line " & $bar & @LF & $_aRawData_[$bar])
                Return SetError(7, 0, __Return($_aRawData_)) ; Missing Parentheses
            EndIf

            $_aScriptArr_[$foo] = StringTrimLeft(StringTrimRight($_aScriptArr_[$foo], 1), 1)
            $_temp_ = Execute($_aScriptArr_[$foo])
            $_error_ = @error

            If StringLen($_temp_) = 0 Or ($_temp_ <> 0 And $_error_ <> 0 And (Not IsNumber(Number($_temp_)) Or $_temp_ = False)) Then
                $_aTemp_ = StringRegExp($_aScriptArr_[$foo], "x24w+", 3)

                If Not @error Then
                    For $bar = 0 To UBound($_aTemp_) -1
                        $_temp_ = StringTrimLeft($_aTemp_[$bar], 1)
                        If Not IsDeclared($_temp_) Then
                            $_subLen_ = StringLen($_subStr_)

                            If StringLeft($_temp_, $_subLen_ +1) = "k" & $_subStr_ Then ; Or StringLeft($_temp_, $_subLen_ +1) = "n" & $_subStr_ ; may need to add this
                                $_temp_ = StringTrimLeft($_temp_, $_subLen_ +1)
                            ElseIf StringLeft($_temp_, $_subLen_) = $_subStr_ Then
                                $_temp_ = StringTrimLeft($_temp_, $_subLen_)
                            EndIf

                            $bar = __GetBreakPoint($_sRawCode_, $foo, $_temp_)
                            MsgBox(16, "Error", __ErrorMsg(8) & @LF & "Line " & $bar & @LF & $_aRawData_[$bar])
                            Return SetError(8, 0, __Return($_aRawData_))
                        EndIf
                    Next
                EndIf
                MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo])
                Return SetError(2, 0, __Return($_aRawData_))
            EndIf

            $_aRawData_[$bar] = StringStripWS(StringRegExpReplace($_aRawData_[$bar], "(;.*)", ""), 2) & " ;= " & $_temp_
        Else ; No assignments or Echo function - just an expression. What's that all about?
            $_temp_ = Execute($_aScriptArr_[$foo])
            $_error_ = @error
            If StringLen($_temp_) = 0 Or ($_temp_ <> 0 And $_error_ <> 0 And Not IsNumber(Number($_temp_)) Or $_temp_ = False) Then
                MsgBox(16, "Error", __ErrorMsg(2) & @LF & "Line " & $foo & @LF & $_aRawData_[$foo])
                Return SetError(2, 0, __Return($_aRawData_))
            EndIf
        EndIf
    Next

    Return __Return($_aRawData_)
EndFunc ;==> _Execute


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __GetNewStr
; Description ...: Searches for a nonconflicting substitution string to replace the dollar sign.
; Syntax.........: __GetNewStr($sTestStr, ByRef $sNewString)
; Parameters ....: $sTestStr - AutoMathEdit
;               : $sNewString - substitution string
; Return values .: [ByRef] $sNewString
; Author ........: czardas
; Modified.......:
; Remarks .......: Avoids conflicts by placing underscore in the second character position.
; Related .......: __GetSubArr
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __GetNewStr($sTestStr, ByRef $sNewString) ; Find a nonconflicting replacement for $ (dollar sign)
    Local $aChar[37] = ["_","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] ; Move outside function

    If StringLen($sNewString) < 2 Then $sNewString = $aChar[Random(0, 36, 1)] & "_"
    If Not StringInStr($sTestStr, $sNewString) Then Return

    For $i = 0 To 36
        If Not StringInStr($sTestStr, $sNewString & $aChar[$i]) Then
            $sNewString &= $aChar[$i]
            Return
        EndIf
    Next

    $sNewString &= $aChar[Random(0, 36, 1)]
    __GetNewStr($sTestStr, $sNewString)
EndFunc ;==> __GetNewStr


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __GetSubArr
; Description ...: Searches for a nonconflicting substitution string to replace the dollar sign.
; Syntax.........: __GetNewStr($sTestStr, ByRef $sNewString)
; Parameters ....: $sTestStr - AutoMathEdit
;               : $subStr - substitution string
;               : $sFail - Unexpected string which caused the function to fail
;               ; Return values .: Success   - An array of variable name substitutions
;                 Failure   - Sets @error and returns [ByRef] $sFail
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: __GetNewStr
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __GetSubArr($sTestStr, $subStr, ByRef $sFail)

    __StripOutStrings($sTestStr) ; Remove quotes

    Local $aRegExp = StringRegExp($sTestStr, "[^,w=-^*+()x24s.x22'/]", 3)
    If Not @error Then ; Encountered an illegal character
        $sFail = $aRegExp[0]
        Return SetError(1) ; Illegal character
    EndIf

    $aRegExp = StringRegExp($sTestStr, "([w|x24]x24)|(x24[^w])", 3)
    If Not @error Then ; Dollar is in the wrong place
        $sFail = $aRegExp[0]
        Return SetError(2) ; Invalid Syntax
    EndIf

    $aRegExp = StringRegExp($sTestStr, "($?w+s*(?)", 3) ; Gets functions and variables

    If IsArray($aRegExp) Then
        For $i = 0 To UBound($aRegExp) -1
            $aRegExp[$i] = StringLower(StringStripWS($aRegExp[$i], 3)) ; Account for case insensitivity
        Next

        $aRegExp = _ArrayUnique($aRegExp) ; Get rid of duplicated substitution strings
        Local $aSubArr[UBound($aRegExp) +1][2]
        $aSubArr[0][0] = 0

        For $i = 0 To UBound($aRegExp) -1
            $aRegExp[$i] = StringStripWS($aRegExp[$i], 2)
            Select
                Case StringRight($aRegExp[$i], 1) = "("
                    If StringLeft($aRegExp[$i], 1) = "$" Then ; Functions do not begin with $
                        $sFail = $aRegExp[$i]
                        Return SetError(2) ; Invalid Syntax
                    ElseIf Not (__IsFunc(StringRegExpReplace($aRegExp[$i], "s*(", "")) Or StringStripWS($aRegExp[$i], 8) = "_(") Then
                        $sFail = $aRegExp[$i]
                        Return SetError(3) ; Function not recognised
                    EndIf

                Case StringLeft($aRegExp[$i], 1) = "$"
                    If __IsReserved(StringTrimLeft($aRegExp[$i], 1)) Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = StringReplace($aRegExp[$i], "$", "$r" & $subStr)
                    ElseIf Not __IsConst(StringTrimLeft($aRegExp[$i], 1)) Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = StringReplace($aRegExp[$i], "$", "$o" & $subStr)
                    EndIf

                Case StringLeft($aRegExp[$i], 2) = "0x"
                    If Not StringIsXDigit(StringTrimLeft($aRegExp[$i], 2)) Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = "$x" & $subStr & $aRegExp[$i]
                    EndIf
                Case Not (StringIsInt($aRegExp[$i]) Or StringIsFloat($aRegExp[$i]) Or __IsFunc($aRegExp[$i]))
                    If __IsReserved($aRegExp[$i]) Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = "$r" & $subStr & $aRegExp[$i]
                    ElseIf __IsConst($aRegExp[$i]) Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = "$k" & $subStr & $aRegExp[$i]
                    ElseIf StringIsDigit(StringLeft($aRegExp[$i], 1)) Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = "$d" & $subStr & $aRegExp[$i]
                    ElseIf $aRegExp[$i] <> "_" Then
                        $aSubArr[0][0] += 1
                        $aSubArr[$aSubArr[0][0] ][0] = $aRegExp[$i]
                        $aSubArr[$aSubArr[0][0] ][1] = "$w" & $subStr & $aRegExp[$i]
                    EndIf
            EndSelect
        Next
        ReDim $aSubArr[$aSubArr[0][0] +1][2]

        For $i = 0 To $aSubArr[0][0]
            $aSubArr[$i][0] = StringReplace($aSubArr[$i][0], "$", $subStr)
        Next

        Return $aSubArr ; No errors have occured.
    Else
        Return SetError(4) ; Unexpected Termination
    EndIf
EndFunc ;==> __GetSubArr


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __StripOutStrings
; Description ...: Removes all strings wrapped in quotes from the code.
; Syntax.........: __StripOutStrings(ByRef $sCodeStr)
; Parameters ....: $sCodeStr - The string to alter.
; Return values .: [ByRef] the string after removing all strings wrapped in quotes
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: None
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __StripOutStrings(ByRef $sCodeStr)
    Local $foo, $bar, $iStart, $iEnd, $aQuot

    While 1
        $foo = StringInStr($sCodeStr, '"') ; Double quote
        $bar = StringInStr($sCodeStr, "'") ; Single quote
        If $foo = 0 And $bar = 0 Then ExitLoop
        If $foo > $bar And $bar > 0 Then
            $iStart = $bar
            $sQuot = "'"
        Else
            $iStart = $foo
            $sQuot = '"'
        EndIf

        $iEnd = StringInStr($sCodeStr, $sQuot, 0, 2)
        If $iEnd = 0 Then ; Error Code???
            $sCodeStr = StringLeft($sCodeStr, $iStart -1)
        Else
            $sCodeStr = StringLeft($sCodeStr, $iStart -1) & " " & StringRight($sCodeStr, StringLen($sCodeStr) - $iEnd)
        EndIf
    WEnd
EndFunc ;==> __StripOutStrings


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __IsConst
; Description ...: Checks to see if the string is the name of a constant.
; Syntax.........: __IsFunc($sTestStr)
; Parameters ....: $sTestStr - Variable name to test
; Return values .: Returns True or False
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: __IsFunc , __IsReserved
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __IsConst($sTestStr)
    $sTestStr = "|" & $sTestStr & "|"
    If StringInStr("|MATH_E|MATH_PHI|MATH_PI|MATH_PSI|", $sTestStr) Then
        Return True
    Else
        Return False
    EndIf
EndFunc ;==> __IsConst


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __IsFunc
; Description ...: Checks to see if the string is the name of a function.
; Syntax.........: __IsFunc($sTestStr)
; Parameters ....: $sTestStr - Name to test
; Return values .: Returns True or False
; Author ........: czardas
; Modified.......:
; Remarks .......: Only recognises AutoMathEdit functions
; Related .......: __IsConst , __IsReserved
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __IsFunc($sTestStr)
    $sTestStr = "|" & $sTestStr & "|"
    If StringInStr("|_ATan2|_Combinations|_Degree|_Factorial|_Max|_Min|_Permutations|_Radian|Abs|ACos|ASin|ATan|BitAND|BitNOT|BitOR|BitRotate|BitShift|BitXOR|Ceiling|Cos|Dec|Echo|Exp|Floor|Hex|Log|Mod|Random|Round|Sin|Sqrt|Tan|", $sTestStr) Then
        Return True
    Else
        Return False
    EndIf
EndFunc ;==> __IsFunc


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __IsReserved
; Description ...: Checks to see if the variable name is already being used.
; Syntax.........: __IsReserved($sTestStr)
; Parameters ....: $sTestStr - Variable name to test
; Return values .: Returns True or False
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: __IsConst , __IsFunc
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __IsReserved($sTestStr)
    $sTestStr = "|" & $sTestStr & "|"
    If StringInStr("|_subStr_|_in|no_|_error_|_sFail_|_sRawCode_|_aAssign_|_nValue_|_sScript_|_temp_|_aTemp_|_subLen_|_aScriptArr_|_aRawData_|", $sTestStr) Then
        Return True
    Else
        Return False
    EndIf
EndFunc ;==> __IsReserved


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __AssignSplit
; Description ...: Splits an assignment command to var = expression
; Syntax.........: __AssignSplit($sAssignStr)
; Parameters ....: $sAssignStr - Line of code containing an assignment operator
; Return values .: An array where:-
;               | element 0 = type of assignment = += -= *= /=
;               | element 1 = variable name
;               | element 2 = expression
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: None
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __AssignSplit($sAssignStr)
    Local $aAssignArr = StringSplit($sAssignStr, "=") ; Split string => variable equals expression
    If $aAssignArr[0] > 2 Then Return SetError(2, 0, 0) ; Only one assignment allowed per line

    Switch StringRight($aAssignArr[1], 1)
        Case "+","-","*","/" ; Get type of assignment
            $aAssignArr[0] = StringRight($aAssignArr[1], 1) ; += or -= or *= or /=
            $aAssignArr[1] = StringTrimRight($aAssignArr[1], 1)
        Case Else
            If StringRegExp($aAssignArr[1], "([+-*/][s]+z)") Then Return SetError(2)
    EndSwitch
    $aAssignArr[1] = StringStripWS($aAssignArr[1], 3)
    Return $aAssignArr
EndFunc ;==> __AssignSplit


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __GetBreakPoint
; Description ...: Determines the exact line where a break in operations occurs - an error or a closing bracket for Echo
; Syntax.........: __GetBreakPoint($scriptStr, $iPosition [, $sErrorStr = False [, $iOccurence = 1 ]] )
; Parameters ....: $scriptStr - AutoMathEdit
;               : $iPosition - Line to start the search
;               : $sErrorStr - Unexpected string which caused the function to fail
;               : $iOccurence - The occurence of the error string to find.
; Return values .: The line number from the original script where the break in operations occured.
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: None
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __GetBreakPoint($scriptStr, $iPosition, $sErrorStr = False, $iOccurence = 1)
    Local $aScriptArr = StringSplit(StringStripCR($scriptStr), @LF), $iCount = 0

    Switch $sErrorStr
        Case "="
            For $i = $iPosition To $aScriptArr[0]
                If StringRegExp($aScriptArr[$i], "(s_s*z)") Then
                    While StringInStr($aScriptArr[$i], $sErrorStr, 0, 1)
                        $aScriptArr[$i] = StringReplace($aScriptArr[$i], $sErrorStr, "", 1)
                        $iCount += 1
                        If $iCount = $iOccurence Then Return $i
                    WEnd
                Else
                    Return $i
                EndIf
            Next

        Case False
            While StringRegExp($aScriptArr[$iPosition], "(s_s*z)")
                $iPosition += 1
                If $iPosition > $aScriptArr[0] Or $aScriptArr[$iPosition -1] = "" Then Return SetError (5, 0, $iPosition) ; Unterminated string
            WEnd
            Return $iPosition

        Case Else
            For $iPosition = $iPosition To $aScriptArr[0]
                If StringRegExp($aScriptArr[$iPosition], "(x24" & $sErrorStr &"[^w])") Or StringRegExp($aScriptArr[$iPosition], "([^w]" & $sErrorStr &"[^w])") Then Return $iPosition
            Next
    EndSwitch
EndFunc ;==> __GetBreakPoint


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __ErrorMsg
; Description ...: Returns the details of an error encountered while parsing the script.
; Syntax.........: __ErrorMsg($vError)
; Parameters ....: $vError - Error code 1 - 8
; Return values .: $vError - Details of the type of error encountered.
; Author ........: czardas
; Modified.......:
; Remarks .......:
; Related .......: None
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __ErrorMsg($vError)
    Switch $vError
        Case 1
            $vError = "Illegal characters"
        Case 2
            $vError = "Invalid Syntax"
        Case 3
            $vError = "Function not recognised"
        Case 4
            $vError = "Unexpected Termination"
        Case 5
            $vError = "Unterminated String"
        Case 6
            $vError = "Failed to reassign mathematical constant"
        Case 7
            $vError = "Missing Parentheses"
        Case 8
            $vError = "Unassigned Variable"
    EndSwitch
    Return $vError
EndFunc ;==> __ErrorMsg


; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: __Return
; Description ...: Same as _ArrayToString, but with parameters already set
; Syntax.........: __Return($aRawData)
; Parameters ....: $aRawData - an array with the original script plus added comments.
; Return values .: Original script plus comments.
; Author ........: czardas
; Modified.......:
; Remarks .......: This function only exists to simplify reading the code for _Execute.
; Related .......: None
; Link ..........:
; Example .......: No
; ===============================================================================================================================

Func __Return($aRawData)
    Return _ArrayToString($aRawData, @CRLF, 1)
EndFunc ;==> __Return


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#region ;... External library not yet complete
Func _Permutations($n, $k)
    If Not IsInt($n) Or Not IsInt($k) Then Return SetError(1)
    If $k > $n Then Return 0
    Return _Factorial($n)/(_Factorial($n -$k))
EndFunc ;==> _Permutations

Func _Combinations($n, $k)
    If Not IsInt($n) Or $n < 1 Or Not IsInt($k) Or $k < 1 Then Return SetError(1)
    If $k > $n Then Return 0
    Return _Factorial($n)/(_Factorial($k)*_Factorial($n -$k))
EndFunc ;==> _Combinations

Func _Factorial($n) ; From UEZ
    If Not IsInt($n) Or $n < 1 Then Return SetError(1)
    Local $iRet = 1
    For $i = 1 to $n
        $iRet *= $i
    Next
    Return $iRet
EndFunc
#endregion

Test Edit Control

#include <WindowsConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <WinAPI.au3>
#include <AutoMathEdit.au3>

_MathEditorTest()

Func _MathEditorTest()
Local $hGUI = GUICreate("AutoMathScript Edit Control Test", 600, 400, Default, Default, BitOR($WS_OVERLAPPEDWINDOW, $WS_EX_COMPOSITED))
Local $hFileMenu = GUICtrlCreateMenu("File")

Local $hExit = GUICtrlCreateMenuItem("Exit", $hFileMenu), _
$hTools = GUICtrlCreateMenu("Tools")

Local $hExecute = GUICtrlCreateMenuItem("Execute" & @TAB & "F5", $hTools), _
$iyOffset = _WinAPI_GetSystemMetrics(55) ; SM_CYMENUSIZE

Local $hEdit1 = GUICtrlCreateEdit("", 0, 0, 600, 400 - $iyOffset, BitOr($GUI_SS_DEFAULT_EDIT, $ES_NOHIDESEL)), _
$hF5 = GUICtrlCreateDummy(), _
$hTab = GUICtrlCreateDummy(), _
$hSelectAll = GUICtrlCreateDummy(), _
$AccelKeys[3][2] = [[ @TAB, $hTab],["^a", $hSelectAll],["{F5}", $hF5]]

GUICtrlSetFont($hEdit1, 12, 400, 1, "Lucida Console")
GUISetAccelerators($AccelKeys)
GUISetState()

While 1
     $msg = GUIGetMsg()
     Switch $msg
         Case $GUI_EVENT_CLOSE, $hExit
             ExitLoop
         Case $hExecute, $hF5
             $sRet = _Execute(_GetSelectedText($hEdit1))
             _GUICtrlEdit_ReplaceSel($hEdit1, $sRet)
         Case $hTab
             _TAB($hEdit1)
         Case $hSelectAll
             _SelectAll($hEdit1)
     EndSwitch
WEnd
EndFunc ;==> _MathEditorTest

Func _GetSelectedText($hEdit)
Local $aPos = _GUICtrlEdit_GetSel($hEdit)
If $aPos[0] = $aPos[1] Then Return SetError(1, 0, "") ; Nothing selected
$sRet = StringMid(_GUICtrlEdit_GetText($hEdit), $aPos[0] +1, $aPos[1] - $aPos[0])
Return $sRet
EndFunc ;==> _GetSelectedText

Func _TAB($hEdit)
Local $sSelText = _GetSelectedText($hEdit)
If Not @error Then
     Local $aLines = StringSplit($sSelText, @CRLF, 1)
     If $aLines[0] > 1 Then
         For $i = 1 To $aLines[0]
             $aLines[$i] = @TAB & $aLines[$i]
         Next
         _GUICtrlEdit_ReplaceSel($hEdit, _ArrayToString($aLines, @CRLF, 1))
         Return
     EndIf
EndIf
_GUICtrlEdit_ReplaceSel($hEdit, @TAB)
EndFunc ;==> _TAB

Func _SelectAll($hEdit)
_GUICtrlEdit_SetSel($hEdit, 0, -1)
EndFunc ;==> _SelectAll

See next post for features, history and AutoMathEdit examples.

Edited by czardas
Link to comment
Share on other sites

Features:

AutoMathEdit has no keywords and all variables are declared automatically.

The dollar sign $ is optional for naming variables. - this feature works with the current version of AutoIt.

Variable types include integers, binary and floats.

Underscore can be used to continue after a line break.

Current Functions:

_ATan2 , _Combinations , _Degree , _Factorial , _Max ,_Min , _Permutations , _Radian

Abs , ACos , ASin , ATan , BitAND , BitNOT , BitOR , BitRotate , BitShift , BitXOR , Ceiling , Cos , Dec

Echo , Exp , Floor , Hex , Log , Mod , Random , Round , Sin , Sqrt , Tan

Known Bugs:

06/07/2012 : Error messages sometimes return the wrong line number. (low priority)

07/08/2012 :Exponential numeric input not recognized unless passed as a string. (high priority)

07/08/2012 :Declaring values equal to zero fails (fixed but not yet released)

Bug Fixes

06/07/2012 : The value zero not recognized as being a number - Fixed in Alpha version 0.0.0.2

07/07/2012 : Variable names beginning with a number not wortking - Fixed in Alpha version 0.0.0.3

07/07/2012 : Empty strings not returning an error - Fixed in Alpha version 0.0.0.4

07/07/2012 : Conflicts with duplicate variable names - Fixed in Alpha version 0.0.0.6

Change Log

07/07/2012 : Name changed from AutoMathScript to AutoMathEdit => Alpha version 0.0.0.5

Examples

; Instructions:
; Select and highlight one or more examples with the mouse.
; Press F5 to run the script

; Example 1
    Echo(_Permutations(3,2))

; Example 2
    Echo(_Combinations(4,3))

; Example 3
    Echo(Hex(16843009))

; Example 4
    Echo(Dec("F69B5"))

; Example 5
    Echo((BitOR(0x0F,0xF0) +1)^.125)

; Example 6
    Echo(Ceiling(Tan(0x3A)))

; Example 7
    _trancexx = 0X7FFF/5
    Echo(Round(_trancexx, 12))

; Example 8
    $FF = 0xFF +1
    $FF/=8
    Echo($FF)

; Example 9
    MsgBox = $MATH_PI
    global = $MATH_PSI
    Echo(Random( _
    MsgBox, _
    global))

; Example 10
    A  = 0xA
    _A = 0xB ; <== no conflict
    A_ = 0xC
    1A = 0xD
    $A = 0xE

    Echo (A*_A*A_*1A*$A)

If you don't select anything then nothing will happen. There should be an error message => Please select something and try again. That you will have to add yourself.

The advantage to using AutoMathEdit is that you don't need to create a new document to run a new bit of code. You can keep all your maths workings out in a single text document and run any part of the code you wish. That's the whole idea behind this project. Posted Image

Edited by czardas
Link to comment
Share on other sites

Thank for this _execute udf.

Try this TooltipExecute.au3:

;==============================================
; Tooltip Execution Example
; by Valery Ivanov, July 2012
; based on http://www.autoitscript.com/forum/topic/142184-automathedit/
;==============================================
#Include <Misc.au3>
#include <AutoMathEdit.au3>
Opt("GUICloseOnESC",0)
HotKeySet("^`", "ExecIt") ; <Ctrl-`>
GUICreate('', -1, -1, -1, -1, -1, 0x80)
While 1
Sleep(50)
If _IsPressed('04') Then ExecIt()
WEnd
;=========================================
func ExecIt()
local $sRes, $Expression
local $res, $MPos
Send ("^c")
Sleep(100)
$Expression = StringStripWS(ClipGet(),3)
$MPos = MouseGetPos()
$sRes = _Execute($Expression)
$sParts = StringSplit($sRes,@Lf)
$sRes = ''
for $i = 1 to $sParts[0]
$sRes &= StringStripWS($sParts[$i],3) & @Lf
next
$sRes = StringTrimRight($sRes,1)
if not @error then ToolTip($sRes, $MPos[0], $MPos[1])
Sleep(2000)
ToolTip('')
endfunc

How it works.

- Start it

- Select by mouse expression(s) in any place (incl. _MathEditor from Test example)

- Press keystroke {Ctrl-`} or Middle button of mouse (if it is not already used)

- See result in tooltip window (2 seconds)

Edited by ValeryVal

The point of world view

Link to comment
Share on other sites

If anyone can suggest maths functions or constants that you think would be useful for this, I would be grateful.

It would be useful to haveWolfram_Evalutation UDF.

Allows to get into AutoIt the results of Wolfram Evaluator on some expression like this page:

http://www.wolframalpha.com/

Edited by ValeryVal

The point of world view

Link to comment
Share on other sites

ValeryVal, it took me a short while to figure that out. Anyway I like it. This UDF of mine needs some serious work though. It seems every time I fix something another bug appears (which I just noticed). (Hmm it seems to be working again, I must have run an older version - still needs work though), I like the tooltip idea a lot. I'll also take a look at the link you provided.

I needed a break from it over the weekend, but hopefully I'll be able to spend time on it and give it a proper testing this week (it's still in aplha phase ATM). At least the examples are working alright. :)

Edited by czardas
Link to comment
Share on other sites

  • 8 months later...

AutoMathEdit - not the language, the program

I would have liked to have got further with this project but so many things seem to have gotten in the way. Anyway I have decided to release an alpha version of the actual AutoMathEdit program. It features the above code with one or two minor fixes, but that's only one of several unfinished features. Most things work as intended and the program seems stable enough - it's just not finished. I'm releasing it now because I don't know how long it will take to finish it. The code is not included, but you can find the code for several of the features in and also in some other posts of mine.

The advanced editor features generally only operate on text which is selected. The basic editor features are pretty much the same as in notepad with one or two small exceptions. I find the most useful features are Paste Lines Left and Paste Lines Right. These allow you to paste multilines from the clipboard to the right or left of the lines you select in the editor (multiline concatenation). Using some AutoMathEdit features can be a bit like making a patchwork quilt from text. It's not entirely linear. You really need to think out of the box to reap full benefit from this program. B)

Download AutoMathEdit.exe

SHA-1 of the zip file is:

961D82B3A6A13868731DEF1018C7507CA454C9B2

Screenshots (these are old screenshots)

Posted Image

Posted Image

Posted Image

I hope you enjoy using this tool as much as I do, and that it also has educational value for others - as it has for me. Give it a try: I'm pretty sure you'll find several of the features very useful. :)

If there's anything you don't understand, please ask. The help file still needs to be written. The program does not currently store user settings and a few other non-essential routines need adding, Apart from that everything works. The program is bundled with - see first screenshot. The keyboard may only be useful if your computer uses the win-1252 code page which is the default on most machines in the USA and Europe.

Edited by czardas
Link to comment
Share on other sites

I found an error and believe you me I take no pleasure in reporting this. Insert >> Date/Time type in the combo box insert 'blah', select 'Month Name' and then hit OK, voila out of bounds array error.

All in all, some nice ideas there. Thanks.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I found an error and believe you me I take no pleasure in reporting this. Insert >> Date/Time type in the combo box insert 'blah', select 'Month Name' and then hit OK, voila out of bounds array error.

All in all, some nice ideas there. Thanks.

Okay, thanks guinness, I'll take a look at it. I'm happy you reported it. :)

Link to comment
Share on other sites

I would just make the combo read-only. I find most of my coding time is spent wondering "What would an average user do?"

Edited by guinness

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I would just make the combo read-only. I find most of my coding time is spent wondering "What would an average user do?"

Thanks, it was my first thought too, however the code to fix the issue was already there - I just needed to change two numbers. It was a bug which crept in unnoticed during a change I made earlier. I didn't notice it because I made this change to an included script but forgot to alter the code in main program. :doh:

It has now been fixed and a new version uploaded. :)

Edited by czardas
Link to comment
Share on other sites

New Demo - (see spoiler)

So far I haven't said much about the strengths and weaknesses of the program - all programs have weaknesses. Firstly I'll address some of these weaknesses.

The edit control is currently limited to 1050622 characters. This value is based on a 1024 x 1024 square of characters, plus an additional 2046 line break characters. This is the largest possible square of characters (1024 x 1024) that can be rotated without lines wrapping within the edit control. I will later override this limitation but, in addition, word wrap does not perform well with large strings. Contingency measures will be implemented to prevent slow responce times - see the message you get the first time you apply Word Wrap. This problem also affects other programs such as Notepad.

Unicode has partial support. When saving a file, ansi is used by default to facilitate greater compatibility with general purpose applications. If the editor contains unicode then the file is saved as UTF-16. I intend to add settings so you can override this later.

Flexibility of the program is the main objective. I intend to give non-programmers access to some of the common basic functions available to programmers. AutoMathEdit speeds up many menial tasks: such as reformating the syntax of large array declarations (see animation in the spoiler below); or generating csv format by pasting lists of words or data side by side - combined with appending commas of course. When you need to explore the values of certain expressions, such as those generated by bitwise functions, it's very handy to just run a short script within your text file.

Demo / Animation

Posted Image

This is just the beginning for this program. Several features are planned, and both AutoMathEdit.exe and AutoMathEdit script still need more work. Any suggestions are welcome. Some things I may have thought about already but could have been rejected. Syntax highlighting is of low priority and may never be included: simply because other programs are already available which do this. I think it would represent a distraction to the user - contrary to the nature of the beast.

Some of the available features I have not seen in other editors, otherwise I wouldn't have bothered to make this. It doesn't necessarily mean they don't exist - I just don't see them. I will probably add lOCh nESs moNSter cASe. It's impossible to say why anyone might need it though. :blink:


After reading this, please let me know of anything you don't like about AutoMathEdit, and please give your reasons.

Edited by czardas
Link to comment
Share on other sites

Although this tool is intended for general use - I will reiterate - it includes some very useful features and I know you will not be disappointed. Don't let the fact it that it isn't quite finished yet put you off trying it. I will eventually add some hacks for advanced users to stumble upon. Feedback at this stage would be appreciated. I hope you like the animation. I'll make be making a better demo soon - perhaps several.

Edited by czardas
Link to comment
Share on other sites

  • 2 weeks later...

Uploaded a new version - Only a few more things to add now, but these are mainly simple things like disabling menu items, adding a settings panel and a few messages. There are currently 64 features, some of which may be subject to change. There will probably be a delay before any further releases until the open source AutoMathEdit script is completed. There will be approx 50 functions used by the script. About half of them are AutoIt functions, the rest are a combination of practical maths functions and some exploratory maths functions.

Full list of current menu items / features - should just about cover most of your editing requirements.

01. New, 02. Open, 03. Save, 04. Save As, 05. Print, 06. Exit, 07. Undo, 08. Cut, 09. Copy, 10. Paste, 11. Find, 12. Find Next, 13. Replace, 14. Go To, 15. Select All, 16. Word Wrap, 17. Font, 18. Upper Case, 19. Lower Case, 20. Toggle Case, 21. Title Case (settings need adding to options), 22. Proper Case, 23. Camel Case, 24. Loch Ness Monster Case, 25. Change Background, 26. AutoMathEdit Script (experimental and unfinished), 27. Rotate Text 90 degrees Clockwise, 28. Rotate Text 90 degrees Anticlockwise, 29. Rotate Text 180 degrees, 30. Flip Text, 31. Mirror Text, 32. Rotate Text Cylinder, 33. Sort (Lines) Ascending, 34. Sort (Lines) Descending, 35. Sort (Lines) By Number, 36. Sort (Lines) By Line Length, 37. Sort (Lines To) Random Sequence, 38. U+____ To Unicode, 39. Convert To ANSI, 40. Convert To ASCII, 41. ANSI To Hex, 42. Hex To ANSI, 43. Win-1252 Keyboard (US and parts of Europe), 44. Word Frequency, 45. Word Count, 46. Insert Date / Time (currently supports 18 languages), 47. Enumerate Selection (Dec, Hex, Roman Numerals), 48. Prefix Text, 49. Append Text, 50. Paste Lines Left, 51. Paste Lines Right, 52. Convert CR To CRLF, 53. Convert LF To CRLF, 54. Remove Spaces (Trailing, Leading, Double, All), 55. Remove Double Line Breaks, 56. Remove All Line Breaks, 57. Remove Punctuation, 58. Remove Accents, 59. Remove Control Characters, 60. Remove Line Repeats, 61. Trim Lines Left, 62. Trim Lines Right, 63. View Toolbar, 64. View Status Bar

To convert unicode code points to glyphs, use U+ followed by the hex value ==> select the text containing code points and press Ctrl+U. You may need a special unicode font installed to view many of the characters.

New screen shots are still needed.

Completed but not Yet Released (personal reminder).

03/04/13 Feature: Word Count/Frequency - Support for alpha characters from any ANSI code page - Added

08/04/13 Improved removal of diacritics on latin characters - including character combinations. - A different approach by JCHD requires further investigation.

Edited by czardas
Link to comment
Share on other sites

  • 4 months later...

I decided to add a section here with real examples of using AutoMathEdit Script. I haven't abandoned this project, but it's currently fourth on a list of five items. I use the program every day in its unfinished state. The calculation relates to currently unpublished code.

;

EXAMPLE

; An example calculation
; Calculating the number of years it takes to BLINDLY brute force a particular encryption

 ;_________________________AutoMathEdit__________________________

 bytes = 1024 * 1 ; 1KB of encrypted data
 
 bytes += 1024 ; added junk
 
 max_shift = (bytes/2)^.5 ; Only applies to less than 1MB of data
 
 search_space = max_shift^max_shift^2 ; All possible transpositions
 
 echo (search_space) ;= 2.13598703592091e+096
 
 ;_______________________________________________________________
 
 
 current_search_limit = 4*10^7 ; 4e+7 estimated attempts per second
 
 moores_law_correction = 2^15 ; 30 year estimated cut off point
 
 searches_per_sec = current_search_limit * moores_law_correction
 
 echo (searches_per_sec) ;= 1310720000000
 
 ;_______________________________________________________________
 
 
 seconds = search_space / searches_per_sec
 
 years = seconds / (60^2 * 25 * 365)
 
 echo (years) ;= 4.96081820720727e+076
Edited by czardas
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...