سؤال

I have a TextView with assigned non-empty TextBuffer.

How to get current cursor position in TextView? Or how to get current TextIter on cursor?

هل كانت مفيدة؟

المحلول

If you have a TextBuffer bound to the variable "buf", you can easily know where the cursor is. insertmark <- textBufferGetInsert buf is a convenient way to get the "insert" mark, which holds the cursor position. Then, you need the corresponding TextIter: cursoriter <- textBufferGetIterAtMark buf insertmark.

Now, the function textIterGetOffset cursoriter will give the position of the cursor inside the TextBuffer, starting from the first character in the buffer. textIterGetChar cursoriter which returns Maybe Char, will tell you what character there is at that position.

See the documentation of the module Graphics.UI.Gtk.Multiline.TextIter to learn more.

Note that the iter is only valid as long as the buffer remains unchanged. If the buffer contents change, you have to get the iter via the "insert" mark again.

This example code runs well on my machine (but it only shows information if you move the cursor with the arrow keys, not if you insert or delete text):

module Main where

import Graphics.UI.Gtk

main = do
    initGUI
    w <- windowNew
    windowSetDefaultSize w 640 400
    on w objectDestroy mainQuit
    h <- vBoxNew False 8
    b <- textBufferNew Nothing
    t <- textViewNewWithBuffer b
    l <- labelNew Nothing
    on t moveCursor $ showInfo b l
    boxPackStart h t PackGrow 0
    boxPackStart h l PackNatural 0
    containerAdd w h
    widgetShowAll w
    mainGUI

showInfo b l movementStep steps flag = do
    i <- textBufferGetInsert b >>= textBufferGetIterAtMark b
    p <- textIterGetOffset i
    c <- textIterGetChar i
    let cc = case c of
                Nothing -> ""
                Just ch -> [ch]
        info = "Position: " ++ show p ++ "\nMovement step: " ++ show movementStep ++
            "\nSteps: " ++ show steps ++ "\nExtends selection: " ++ show flag ++
            "\nCharacter at cursor: " ++ cc
    labelSetText l info
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top